Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript scope: referencing parent object member from child member's closure

Newbie to JavaScript here.

How do I reference member foo from within member foobar, given that foobar's in a closure?

var priv = {

    foo: "bar",

    foobar: (function() {
        return this.foo === "bar";
    })()

};

The code above fails. In it, this.foo is undefined. If I change this.foo to priv.foo, it's still undefined. How do I reference priv.foo from within the foobar closure?

like image 923
DotNetQuestionDate Avatar asked Nov 04 '22 22:11

DotNetQuestionDate


1 Answers

It's impossible to read any properties of an object in its defination during its initialization since prev will be undefined at that time. When you're trying to call a clojure inside it, it refers to undefined this or priv.

Probably you wanted to write:

foobar: (function() {
    return this.foo === "bar";
})

without () in the end. And then you could call it as priv.foobar();

If you still need to call it, you could define foobar after foo:

var priv = {
    foo: "bar"
};

priv.foobar = (function() {
    return priv.foo === "bar";
})()
like image 142
meze Avatar answered Nov 09 '22 12:11

meze