繁体   English   中英

jquery的回调函数中的范围

[英]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功能现在作为一个回调函数的一部分,范围thisshowIt功能应该是一样的.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM