我正在尝试了解 Javascript 的 function.apply()。你像这样使用它:
f.apply(obj,args)
使用给定参数args
运行函数f
,函数内部使用this
映射到对象obj
.
下面是一个简单的示例,展示了这一切如何让我们跟上进度:
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
酷。因此,我编写了一个函数,使用特定的 jquery 插件来解决 javascript 中的空指针问题。如果 jQuery 集为空,它只是不运行函数:
var applyIfPresent = function(jqObj,func,args){
//only works if jquery has the func you supply
if(jqObj.length){
jqObj[func].apply(jqObj,args);
}
}
我已经运行了简单的测试:applyIfPresent($("input"),"css",["background","blue"]);
看看它是否可以推广到多个元素的 jQuery 集合。它似乎工作正常,但我不知道 jQuery 的内部结构和 this
的用法如何转换为该模式。我喜欢它看起来像魔法一样,但说实话?--我已经学会了有点害怕魔法。
f.apply 或 jQuery 如何解决所有这些问题并使其发挥作用?
最佳答案
没那么神奇,通过上面的例子你似乎已经完全理解了。
当你这样做时
jqObj[func].apply(jqObj,args);
与做的基本相同
$(jqObj).func(args);
关于javascript - 当您将 function.apply 设置为 jQuery 集时,了解 function.apply 中的 "this"arg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9038264/