質問

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.

他のヒント

Here's one approach:

var a=3,b=4;
var obj = {x : function(){return a;}, y : function(){return b;}};
alert(obj.x()); // displays '3'
a=2;
alert(obj.x()); // displays '2'

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'

http://jsfiddle.net/tzfDa/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

You 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

http://jsfiddle.net/b7prK/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top