In other words, let the value be a variable. Something like this:
var a=3,b=4;
var obj = {x : a, y : b};
alert(obj.x); //will display '3'
a=2;
alert(obj.x); //want it to display '2' - how can i accomplish this?
In other words, let the value be a variable. Something like this:
var a=3,b=4;
var obj = {x : a, y : b};
alert(obj.x); //will display '3'
a=2;
alert(obj.x); //want it to display '2' - how can i accomplish this?
Make it a method:
var a = 3,
b = 4,
obj = {
x: function () {
return a;
},
y: b
};
a = 2;
And call it like:
obj.x() // returns 2
DEMO: http://jsfiddle.net/67NwY/2/
Otherwise there's no native (and supported in older browsers) way to get the "live" value of a by using obj.x. Another answer here provides the use of Object.defineProperty that can do this.
You can apply this to obj.y as well, if you wish to do the same.
obj.x to reference the value of aa.a = 2; like the OP originally had. I just feel like it's unnecessary in this scenario. The OP is probably leaving out code/examples, so it could all definitely be restructured to do something like what you have, but not deal with "global" variablesobj, but not a at some point.Make it an object
var a = {
val:3
};
var obj = {x : a};
alert(obj.x.val); //will display '3'
a.val=2;
alert(obj.x.val); //will display '2'
Property getters and setters
Adding to what Ian said, in newer versions of JS, you can use property getters and setters. Ian used the programmatic way of defining them, there's also a literal syntax (since your question title mentions "object literal"). Note that by adding a setter also, we allow setting of the value from obj.x and a;
var a = 3;
var o = {
get x() {
return a;
},
set x(value) {
a = value;
}
};
alert ( o.x ); // 3
a = 2;
alert( o.x ); // 2
o.x = 4;
alert(a); // 4
x property as a reference to the object a. So the alerts show "[object Object]". And if you change it to var obj = {x: a.val}; it still doesn't work because it's still referencing a primitive - jsfiddle.net/tzfDa/1You can do this using property descriptors (as of ECMAScript version 5).
var a = 3;
var obj = {};
Object.defineProperty(obj, "x", { get : function(){ return a; } });
alert(obj.x); // 3
a = 2;
alert(obj.x); // 2
obj.x. It's still a property. I'd say that's very different.obj.x, not obj.x(); if you do alert(typeof obj.x), you get "number", not "function". Simply using methods doesn't achieve this, which may or may not break something