最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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

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

Share Improve this question asked May 31, 2013 at 12:24 yardarratyardarrat 2903 silver badges14 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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 bees 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 ment!

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("click", app.bar.bind(app);

发布评论

评论列表(0)

  1. 暂无评论