I’m trying to wrap my head around Javascript’s function.apply(). You use it like this:
f.apply(obj,args)
to run function f with the given arguments args, with the function’s internal usage of this mapped onto the object obj.
Here’s a simple example to show how that all works to get us up-to-speed:
var o = {
state : 0,
plus : function(){
this.state += 1;
}
}
//o is an object with a state-tracking var and a function that will operate on it
o.state
// 0
o.plus()
o.state
// 1
newO = {state:3}
// newO is similar to the original object, but doesn't have that state-manipulating function
newO.state
// 3
o.plus.apply(newO,[]) // call o's function, but hijack the 'this' reference to point to newO
newO.state
// 4
Cool. So I’ve written a function to solve a null pointer issue in javascript with a particular jquery plugin. If a jQuery set is empty, it just doesn’t run a function:
var applyIfPresent = function(jqObj,func,args){
//only works if jquery has the func you supply
if(jqObj.length){
jqObj[func].apply(jqObj,args);
}
}
I’ve run the simple test: applyIfPresent($("input"),"css",["background","blue"]);
To see if it’ll generalize to a jQuery set of multiple elements. It seems to work fine, but I have no idea how the internals of jQuery and the usage of this translates to that schema. I love that it seems to work like magic, but honestly?–I’ve learned to be a little afraid of magic.
How does f.apply or jQuery figure all that out to make it work?
it’s not that magic, you seem to understand it perfectly by the example above.
when you do
it’s basically the same as doing