简体   繁体   English

Javascript对象文字表示法,使用函数

[英]Javascript object literal notation, using functions

I'm creating an object using literal notation. 我正在使用文字符号创建一个对象。 Is it possible to have some of the properties use previously defined properties as their value? 是否有可能让某些属性使用先前定义的属性作为其值?

For example: 例如:

    var test = {
        prop1: obj1, 
        prop2: obj2,
        prop3: (prop1!=null)?prop1:prop2
    };

If you are trying to do something like var x = { 'a': 1, 'b': xa } then it won't work. 如果您尝试执行var x = { 'a': 1, 'b': xa }那么它将无效。 Since x is not finished being defined. 由于x未完成定义。

But you can do something like 但你可以做点什么

var
    a = 12,
    b = 24,
    c = a + b; // 36

This is because each var definition is interpreted sequentially. 这是因为每个var定义都是按顺序解释的。 Basically equivalent to 基本相当于

var a = 12;
var b = 24;
var c = a + b;

But with objects and arrays the entire definition is interpreted one time. 但是对于对象和数组,整个定义被解释一次。

No and yes. 不,是的。

The following aren't possible: 以下是不可能的:

var o = {
    a : 42,
    b : o.a //raises a TypeError, o is not defined
};

var o = {
    a : b : 42 //raises a SyntaxError, unexpected :
};

The following, however, are: 但是,以下是:

//referencing a pre-existing variable is obviously possible
var ans = 42;
var o = {
    a : ans,
    b : ans
};

var o = {
    a : 42
};
//after the variable has been declared, you can access it as usual
o.b = o.a;

If you feel limited by the value being a single statement, you can always use an anonymous function: 如果您觉得值是单个语句的限制,您可以始终使用匿名函数:

var o = {
    a : (function () {
        doStuff();
        return otherStuff();
    }())
};

to keep your example: 保持你的榜样:

var test = {
  prop1: obj1,
  prop2: obj2,
  prop3: (function () {
    return (test.prop1!=null)?test.prop1:test.prop2;
  })()
};

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

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