Richard Cornford wrote:
java wrote:
>Consider:
var x = {a:3, b:x};
alert(x.b) ==undefined
The right hand side of an assignment expression
is evaluated before the resulting value can be assigned to the left hand
side (it has to be). So at the point of evaluation the object literal
the - x - variable has its default - undefined - value, and so that is
what bets assigned to the object's - b - property.
Of course, evaluation of x on the RHS can be deferred by wrapping it
in a closure:
var x = {a:3, b:function(){return x;}};
alert(x.b().a);
Obviously that's not the same thing as what the OP was trying to do,
but it's a common idiom in functional programming.
Alternatively, with an implementation that supports getters, you can
provide a getter for b that returns x:
var x = {a:3};
x.__defineGetter__("b",function(){return this;});
alert(x.b.a);
though whether that's good practice is debatable. (And in this
particular case, I don't think this has any advantage this has over
simply "x.b=x", as Richard suggested. If you wanted b to evaluate to
x.a, then the getter would do something for you.)
If you're using an implementation that supports defining getters in an
object literal (eg sufficiently recent Mozilla Javascript), then you
can create a closure that will automatically be evaluated, as part of
your object literal:
var x = {a:3, get b(){return this;}};
alert(x.b.a);
which achieves the same result as the OP's example. x.b is not
actually a reference to x, of course; it just returns one when
evaluated. Though I'm not sure whether a Javascript program can
distinguish the two.
--
Michael Wojcik