Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference variable in object literal? [duplicate]

say I have

myfunc({
  var1: 1,
  var2: 2,
})

if i want to have a value that makes use of the current unnamed object, how would I do this?

eg if I wanted

myfunc({
  var1: 1,
  var2: 2,
  var3: this.var1 + this.var2
})

obviously this does not work.

What would the correct syntax be?

like image 465
Hailwood Avatar asked Feb 01 '11 04:02

Hailwood


3 Answers

You could make var3 a function, and calling it will allow you to use 'this':

x= {
    v1:4,
    v2:5,
    v3:function(){return this.v1 + this.v2;}
};

alert(x.v3());
like image 152
david Avatar answered Oct 14 '22 11:10

david


Unfortunately, that isn't possible. While an object literal is being constructed, no external reference to that object exists until the entire literal is evaluated. The only way to use this at this stage is to use a constructor instead:

function MyObject() {
  this.var1 = 1;
  this.var2 = 2;
  this.var3 = this.var1 + this.var2;
}

myfunc(new MyObject());
like image 33
casablanca Avatar answered Oct 14 '22 13:10

casablanca


You can't do it in the notation you're using. An object literal doesn't have any notion of itself in this context.

like image 41
coreyward Avatar answered Oct 14 '22 13:10

coreyward