简体   繁体   English

有没有办法在JavaScript中创建动态对象文字值?

[英]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?

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/ 演示: 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 . 否则,有没有原生(在旧的浏览器支持)的方式获得的“活”值a使用obj.x Another answer here provides the use of Object.defineProperty that can do this. 这里的另一个答案提供了可以执行此操作的Object.defineProperty的使用。

You can apply this to obj.y as well, if you wish to do the same. 如果你想做同样的事情,你也可以将它应用于obj.y

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/ 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. 属性getter和setter添加到Ian所说的,在较新版本的JS中,您可以使用属性getter和setter。 Ian used the programmatic way of defining them, there's also a literal syntax (since your question title mentions "object literal"). Ian使用了编程方式来定义它们,还有一个文字语法(因为你的问题标题提到了“对象文字”)。 Note that by adding a setter also, we allow setting of the value from obj.x and a ; 请注意,通过添加setter,我们允许设置obj.xa的值;

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). 您可以使用属性描述符 (从ECMAScript版本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/ http://jsfiddle.net/b7prK/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM