[英]the scope of this in jquery's callback function
My jquery's event is as follows: 我的jquery活动如下:
$('body').on('click', '.show-it', function (e) {
e.preventDefault();
showIt();
});
function showIt() {...};
In the showIt
function, when I wanna try to access $(this)
, it always return the window
object. 在
showIt
函数中,当我想尝试访问$(this)
,它总是返回window
对象。 As far as I know, because the showIt
function now serves as part of a callback function, the scope of this
in the showIt
function should be the same as in the .show-it
button's click callback function, which is the element clicked. 据我所知,因为
showIt
功能现在作为一个回调函数的一部分,范围this
在showIt
功能应该是一样的.show-it
按钮的点击回调函数,这是一个点击的元素。 But it seems to be not. 但似乎不是。 I have to use
self.showIt.call(this)()
in the callback function to get the right scope of this
. 我必须使用
self.showIt.call(this)()
在回调函数来获得的权利范围this
。 So what is going on behind the scene? 那么现场背后发生了什么?
JQuery uses callback.call(el)
or an equivalent expression to set the value of this
to a given DOM element in a callback function. JQuery使用
callback.call(el)
或等效表达式将this
的值设置为回调函数中的给定DOM元素。 But this does not cascade down to other functions called within that callback. 但是这并没有级联到该回调中调用的其他函数。 Try it out:
试试看:
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());
Output: 输出:
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)
Note that when you call a function that's a property of an object, this
gets bound to that object, no matter what this
is in the calling context, unless the function has been bound previously using Function.bind
. 需要注意的是,当你调用一个函数是一个对象的属性,
this
被绑定到该对象,不管this
是在调用上下文,除非该功能以前使用绑定Function.bind
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.