开发者

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开发者_如何学JAVA 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?


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";
})()


The problem is that you aren't defining a closure - I don't think that there is any way to access foo from your function as priv is not yet initialised.

What exactly are you trying to do? The following is equivalent to what I understand your sample is trying to do, but my guess is that I'm not understanding the problem:

// Set elsewhere
var foo = "bar";

var priv = {
    foo: foo ,
    foobar: foo == "bar"
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜