Search code examples
javascriptjavascript-objectsobject-literal

Is there a way to create a dynamically object literal value in JavaScript?


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?

Solution

  • 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.