$0.04

Who this is not working properly in javascript closure

Ask a question+
0

In the following code, there are two javascript closures. One of the “this” is working fine, but in another, it isn’t. Could you please explain how does scope work on closures.

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();

outputs:

outer func:  this.foo = bar
outer func:  self.foo = bar
inner func:  this.foo = undefined
inner func:  self.foo = bar
add comment

1 Answer

0

finally, I understood how it works!

In the outer function, both this and self refers to myObject and therefore both can properly reference and access foo.

In the inner function, though, this no longer refers to myObject. As a result, this.foo is undefined in the inner function, whereas the reference to the local variable self remains in scope and is accessible there.

Arthur Dilanyan 530
add comment

Your Answer