2013-03-01 127 views
0

我正在尝试在基于数组参数的类中创建属性。你怎么能这样做?如何使用for循环在类中创建对象?

请参阅下面的,所以你可以看到我想要做的事:

function Person(colors) { 
    this.color = (function() { 
     this.color = new Object(); 
     for (q=0; q<colors.length; ++q) { 
      var r; 
      switch (q) { 
       case 0: r = "favorite"; break; 
       case 1: r = "likes"; break; 
       case 2: r = "hates"; break; 
       default: r = q; break; 
      }    
      this.color.r = colors[q]; 
     } 
    }).call(this); 
} 

var people = { 
    george: new Person(["blue", "yellow", "green"]), 
    bob: new Person(["green", "purple", "white"]) 
}; 

console.log(people.george.color.favorite); 

基本上我想要做的事:

this.color = { 
    favorite: colors[0], 
    likes: colors[1], 
    hates: colors[2] 
}; 

使用for循环。有任何想法吗?顺便说一句,我不能确定“this.color = new Object();” this.color里面实际上是有效的,这只是我尝试过的。你还能怎么做?

+1

“使用for循环”---任何实际的原因呢? – zerkms 2013-03-01 03:03:07

+0

为什么不只是传递一个对象作为参数? – elclanrs 2013-03-01 03:04:19

+0

@Korey,有没有解决这个问题的运气?你最终做了什么?“? – 2013-10-21 20:02:06

回答

1

我不知道你为什么这样做,它似乎不是一个好主意。

你的代码有什么问题是你没有使用括号表示法。

更改此:

this.color.r = colors[q]; 

要这样:

this.color[r] = colors[q]; 

支架符号表示“访问其命名被放置在变量r财产”而不是“访问属性命名为R”。

Here is a working example

我建议你考虑使用JavaScript字面对象符号来代替。您的整个代码可以重新考虑为:

var people = { 
    george:{ 
     color:{favorite:"blue",likes:"yellow",hates:"green"} 
    }, 
    bob:{ 
     color:{favorite:"green",likes:"purple",hates:"white"} 
    } 
};