[英]this is bound incorrectly if jquery function is called from a stored variable
我以两种方式调用jQuery函数,一种有效,另一种无效,因为this
绑定不正确。
$('#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将上下文绑定到函数引用,然后调用它。
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;
};
}
是的,当获取方法作为函数引用时,可以将其与对象断开连接。 仅当在对象的上下文中调用函数时,该函数才用作方法,通常使用来完成.
运算符,例如obj.method()
。
如果在没有对象上下文的情况下调用函数,则将全局范围作为上下文(即window
对象)进行调用。 例:
var obj = {
name: "obj",
method: function() { alert(this.name); }
};
obj.method(); // shows the name "obj"
var m = obj.method;
m(); // shows the name of window
m.call(obj); // shows the name "obj"
var obj2 = {
name: "obj2"
};
m.call(obj2); // shows the name "obj2" (using the method from obj)
如果要使其用作方法,则必须以对象作为上下文来调用它:
var obj = $('#my-div');
var fadeOutFn = obj.fadeOut;
fadeOutFn.call(obj);
您可以使用proxy
方法制作一个函数,以正确的上下文调用该函数:
var obj = $('#my-div');
var fadeOutFn = $.proxy(obj.fadeOut, obj);
fadeOutFn();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.