[英]the scope of this in jquery's callback function
我的jquery活动如下:
$('body').on('click', '.show-it', function (e) {
e.preventDefault();
showIt();
});
function showIt() {...};
在showIt
函数中,当我想尝试访问$(this)
,它总是返回window
对象。 据我所知,因为showIt
功能现在作为一个回调函数的一部分,范围this
在showIt
功能应该是一样的.show-it
按钮的点击回调函数,这是一个点击的元素。 但似乎不是。 我必须使用self.showIt.call(this)()
在回调函数来获得的权利范围this
。 那么现场背后发生了什么?
JQuery使用callback.call(el)
或等效表达式将this
的值设置为回调函数中的给定DOM元素。 但是这并没有级联到该回调中调用的其他函数。 试试看:
var o = {
name: "baz",
foo: function() {
console.log(this);
}
}
function foo() {
console.log(this);
}
function bar() {
console.log(this); // bar's this
foo(); // the global object
foo.call(this); // bar's this
o.foo(); // o
o.foo.call(this); // bar's this
}
bar.call(new Date());
输出:
Thu Feb 13 2014 13:26:47 GMT-0800 (PST)
Window {top: Window, window: Window, location: Location...}
Thu Feb 13 2014 13:26:47 GMT-0800 (PST) VM350:10
Object {name: "baz", foo: function}
Thu Feb 13 2014 13:26:47 GMT-0800 (PST)
需要注意的是,当你调用一个函数是一个对象的属性, this
被绑定到该对象,不管this
是在调用上下文,除非该功能以前使用绑定Function.bind
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.