I do:
outerobject={
a: 1,
b: 2,
c: this.a + this.b,
};
console.log(outerobject.a);
console.log(outerobject.b);
console.log(outerobject.c);
I expect:
1
2
3
I get:
1
2
NaN
Why do I get a NaN?
I do:
outerobject={
a: 1,
b: 2,
c: this.a + this.b,
};
console.log(outerobject.a);
console.log(outerobject.b);
console.log(outerobject.c);
I expect:
1
2
3
I get:
1
2
NaN
Why do I get a NaN?
Within the object this is assigned a reference to the window or the global object. You need to use a function which will have this refer to a reference of the object.
var outerobject={ a: 1, b: 2, c: function(){return this.a + this.b}};
var outerobject2={ a: 1, b: 2, c: console.log(this)}; //logs window/global object
console.log(outerobject.c());//outputs 3
or use a function constructor:
function MyObject(){
this.a = 1;
this.b = 2;
this.c = this.a + this.b;
console.log(this);
}
var myObject = new MyObject();
The key is the function determines the scope of this. When a function is called as a method of an object, its this is set to the object the method is called on.
JS Fiddle: http://jsfiddle.net/aRFLn/
You probably want to get the sum of property values a and b. You'll need a getter for this:
var outerobject = {
a: 1, // inside a property value `this` is `window`
b: 2,
get c() {
return this.a + this.b; // inside a getter function 'this' is `outerobject`
}
};
Then you can use outerobject.c. It will also be re-evaluated each time you call it:
outerobject.c; // 3
outerobject.a++;
outeobject.c; // 4
In your case 'this' could be any number of things depending on where this is being called. In your case it most likely is the window object. Since window probably doesn't have a and b defined so you get NaN.
Here's a good example on how this works: http://www.quirksmode.org/js/this.html