简体   繁体   中英

javascript - "this" is undefined when method is bound to event listener

I already tried to understand what the this keyword refers to by reading about it. well, that didn't help. so please help me on this one!
where is the difference between the manual function call and the binding to the event listener?

var app = {
    foo: true,
    bar: function() {
        console.log("this",this.foo);
        console.log("app",app.foo);
    }
}

app.bar();
/*  this true
    app true    */

document.addEventListener("click", app.bar);
/*  this undefined
    app true    */

thanks for helping

Inside your document.addEventListener this will refer to document , since you are calling a function of document object. When you are calling app.bar() directly, this refers to app object for the same reason.
If you want to refer to app you have to manually redefine function's context, using bind() :

document.addEventListener("click", app.bar.bind(app));

it is not this , but foo that is undefined because this is document when app.bar is bound as event listener to document . So this.foo becomes document.foo which is undefined.

document.foo = "document.foo";

var app = {
    foo: true,
    bar: function() {
        console.log("this",this.foo);
        console.log("app",app.foo);
    }
};

app.bar();
/*  this true
    app true    */

document.addEventListener("click", app.bar);
/*  this document.foo
    app true    */

you can bind the context

document.addEventListener("click", app.bar.bind(app));

or use a function to call app.bar

document.addEventListener("click", function(event){
    app.bar();
});

I had a lucky hit here... tried it with the module pattern
I never got closures but they seem to work for me here. If anybody's got a good read about closures, please comment!

var app = (function() {
    var foo = true;

    return {
        bar: function() {
            console.log(foo);
        }
    };

})();

app.bar(); //true
document.addEventListener("click", app.bar); //true

EDIT: Sorry, I just figured that this has nothing to do with the this keyword anymore.

document.addEventListener("点击", app.bar.bind(app);

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