简体   繁体   中英

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. Since x is not finished being defined.

But you can do something like

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

This is because each var definition is interpreted sequentially. 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;
  })()
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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