我以两种方式调用 jQuery 函数,一种有效,另一种无效,因为 this
绑定(bind)不正确。
$('#my-div').fadeOut();
按预期工作,fadeOut
函数内的 this
的值是 jQuery 对象。
var fadeOutFn = $('#my-div').fadeOut;
fadeOutFn();
不起作用,因为this
的值现在是Window
这是包含两个示例的 jsfiddle。
编辑:添加一些关于我发布该问题的原因的说明,我真的不想知道如何解决此问题。这不是问题。我想了解为什么会发生这种情况。
最佳答案
是的,它不知道要应用fadeOut
动画的元素,并且在这种情况下,this
上下文主要是窗口而不是jquery对象。您可以使用 function.call
试试这个:
var fadeOutFn = $('#my-div').fadeOut;
fadeOutFn.call($('#my-div'));
或者只是这样做:
使用 function.bind 将上下文绑定(bind)到函数引用,并调用它。
var fadeOutFn = $().fadeOut.bind($('#my-div'));
fadeOutFn();
对于不支持的浏览器,您可以将其添加到 js 文件中以获取文档中提到的支持:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
关于javascript - 如果从存储变量调用 jquery 函数,则此绑定(bind)不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17328967/