in jquery proxy fn
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
what is the main usage for the syntax 2, (context, string)?
asked Mar 18, 2014 at 15:41
user2167582
6,46816 gold badges73 silver badges135 bronze badges
-
see jsfiddle.net/arunpjohny/Yv8hY/1 - api.jquery.com/jQuery.proxy/#example-1Arun P Johny– Arun P Johny2014年03月18日 15:57:42 +00:00Commented Mar 18, 2014 at 15:57
-
See the second example on the documentation for jQuery.proxy.user400654– user4006542014年03月18日 15:57:48 +00:00Commented Mar 18, 2014 at 15:57
1 Answer 1
It's ensuring the passed in context variable is present as an argument (and is also a string) before assigning the data within the fn object with a key of context to the tmp variable.
Without doing this, if we just called $.proxy(fn) with no context argument, the fn variable would end up as undefined and the proxy function itself would return undefined instead of simply ignoring the context variable altogether and processing as if it weren't passed in in the first place.
answered Mar 18, 2014 at 15:58
James Donnelly
129k35 gold badges215 silver badges224 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js