简体   繁体   中英

the scope of this in jquery's callback function

My jquery's event is as follows:

$('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. 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. 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 . 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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