1. jquery.proxy
接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文语境。
jQuery.proxy( function, context )
function将要改变上下文语境的函数。
context函数的上下文语境(`this`)会被设置成这个 object 对象。
jQuery.proxy( context, name )
context函数的上下文语境会被设置成这个 object 对象。
name将要改变上下文语境的函数名(这个函数必须是前一个参数 'context' 对象的属性)
$(function(){ var obj = { name: "John", test: function() { //如果使用$("#button2").click(obj.test);, this.name将是空, 因为this指的是方法本身 //如果使用$("#button2").click(jQuery.proxy( obj, "test" )); this.name将返回John, 因为this指obj对象 alert( this.name ); $("#button2").unbind("click", obj.test); } }; $("#button2").click( jQuery.proxy( obj, "test" ) ); // This also works: // $("#test").click( jQuery.proxy( obj.test, obj ) ); });
2. 动态增加json属性和值
function addjson{ var obj = {}; obj["name"]="guanrl"; }