2013-03-01 133 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"} 
    } 
};