5

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?

2 Answers2

2

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";
})()
meze
  • 14,975
  • 4
  • 47
  • 52
0

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"
};
Justin
  • 84,773
  • 49
  • 224
  • 367
  • In summary, I have a giant JS file. It defines some private variables and a public object. I'm trying to encapsulate these private variables into one object, but each private variable except for one depends on another private variable's value. So instead, assume `foobar` is a run-time, dynamic calculation based off of the value of `foo`. Make sense? – DotNetQuestionDate May 04 '11 at 00:41