开发者

Referring to previously defined properties within an object literal

When using object constructors, properties can be directly assigned to the value of previously defined properties:

var foo = new (function() {
   this.bar = 5;
   this.baz = this.bar;
})();
alert(foo.baz) // 5

I would like to refer to a previously defined property within an OBJECT LITERAL:

var foo = {
   bar : 5,
   baz : bar
}
alert (foo.baz) // I want 5, but evaluates to undefined

I know that I could do this:

var foo = {
   bar开发者_如何转开发 : 5,
   baz : function() {
      alert(this.bar); // 5
   }

But I want to assign baz directly to a value rather than a function. Any ideas?


No, you won't be able to use any properties of the object literal before it has been created. Your closest option is probably to use a temporary variable like so:

var tmp = 5,
    foo = {
       bar : tmp,
       baz : tmp
    }

If you are free to use ECMAScript 5 features, you could write a getter function for the baz property that instead returns the value of bar:

var yourObject = {
    bar: 5
};
Object.defineProperty(yourObject, 'baz', {
    get: function () { return yourObject.bar; }
});


You can also just build a literal by parts:

var foo = {bar:5};
foo.baz = foo.bar;

If you need to fit this inside an expression (instead of through multiple statements) you can try abusing the comma operator or you can make a helper function:

(Warning: untested code)

function make_fancy_object(base_object, copies_to_make){
     var i, copy_from, copy_to_list;
     for(copy_from in copies_to_make){
         if(copies_to_make.hasOwnProperty(copy_from)){
             copy_to_list = copies_to_make[copy_from];
             for(var i=0; i<copy_to_list.length; i++){
                 base_object[copy_to_list[i]] = base_object[copy_from];
             }
          }
      }
}

var foo = make_fancy_object(
    {bar: 5},
    {bar: ["baz", "biv"]}
);

//foo.baz and foo.biv should be 5 now as well.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜