This will not help. How get obj
of the property sum?
var obj = {
a: {
value: 1
},
b: {
value: 2
},
sum: {
value: obj.a.value + obj.b.value
}
};
console.log(obj.sum);
This will not help. How get obj
of the property sum?
var obj = {
a: {
value: 1
},
b: {
value: 2
},
sum: {
value: obj.a.value + obj.b.value
}
};
console.log(obj.sum);
sum
itself is suppose to be a JavaScript function. So this is valid:
var obj = {
a: {
value: 1
},
b: {
value: 2
},
get sumValue(){
return this.a.value + this.b.value
}
};
You can learn more about object methods here.
you need to use in inline getter to code self-reflecting expressions in literals like that:
var obj = {
a: {
value: 1
},
b: {
value: 2
},
get sum(){
return this.a.value + this.b.value
}
};
console.log(obj.sum); // shows: 3
this is ES5, but often over-looked. it works in all major browsers (even IE8) and node.
the getter syntax is nice because obj.sum
both acts like a number and stays updated automatically as a
and b
change.
of course, it's probably more traditional to use a method (a function) and call it like obj.sum()
, as that indicates to other coders that it's a "computed property" more or less...
Inside the object initializer, the object has not been assigned to the variable obj
yet. Then, obj
is undefined, so you can't use obj.a.value
.
But you can achieve something similar by instantiating an anonymous function:
var obj = new function() {
this.a = {
value: 1
};
this.b = {
value: 2
};
this.sum = {
value: this.a.value + this.b.value
};
};
It looks like you trying to add a method to your Object, if so it should be like so:
var obj = {
a: {
value: 1
},
b: {
value: 2
},
sum:function() {
return this.a.value + this.b.value
}
};
console.log(obj.sum); //Returns the function object
console.log(obj.sum()); //Returns the value 3