嘿, 我是Mofei!
jQuery.proxy(function,obj)

I accidentally saw proxy, which I haven't used before, so I will record it! It was added in jQuery 1.4 and returns a new function that always maintains a specific scope. This method is most useful when event handler functions need to be attached to elements, but their scope actually points to another object. Moreover, the best part is that jQuery can ensure that even if you bind a function that has been processed by jQuery.proxy(), you can still pass the original function to accurately unbind it. Please refer to the example below. This function also has another usage, jQuery.proxy( scope, name ). The first parameter is the object whose scope is to be set. The second parameter is the name of the function to set the scope for (which must be a property of the first scope object). It seems a bit like call/apply, doesn’t it? Example:

var obj = {  name: "John",  test: function() {    alert( this.name );  $("#test").unbind("click", obj.test);  } }; 
$("#test").click( jQuery.proxy( obj, "test" ) );
 // The following code is equivalent to the above line:
 // $("#test").click( jQuery.proxy( obj.test, obj ) );
 // This can be compared with the following line executed alone. 
// $("#test").click( obj.test ); The first two outputs are the specified scope obj, so it pops up John, while the last one this.name will just refer to window.name, popping up undefined.
THE END

More Articles You Might Be Interested In

Did this post inspire any ideas? Share your thoughts in the comments!

avatar

Mofei's Friend (Click to edit)

Don't be shy, just type away!

HI. I AM MOFEI!

NICE TO MEET YOU!