JavaScript Callback Scope

2019-01-03 07:49发布

I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.

function foo(id) {
    this.dom = document.getElementById(id);
    this.bar = 5;
    var self = this;
    this.dom.addEventListener("click", self.onclick, false);
}

foo.prototype = {
    onclick : function() {
        this.bar = 7;
    }
};

Now when I create a new object (after the DOM has loaded, with a span#test)

var x = new foo('test');

The 'this' inside the onclick function points to the span#test and not the foo object.

How do I get a reference to my foo object inside the onclick function?

7条回答
We Are One
2楼-- · 2019-01-03 08:55

this is one of the most confusing points of JS: the 'this' variable means to the most local object... but functions are also objects, so 'this' points there. There are other subtle points, but i don't remember them all.

I usually avoid using 'this', just define a local 'me' variable and use that instead.

查看更多
登录 后发表回答