我正試圖解決這個謎題頭腦Javascript OOP問題。Javascript類和變量引用
所以我有以下類:
var ClassA = function() {
this.initialize();
}
ClassA.prototype = {
methods : ['alpha','beta','gama'],
initialize : function() {
for (var i in this.methods) {
this[this.methods[i]] = function() {
console.log(this.methods[i]);
}
}
}
}
var a = new ClassA();
當我打電話每一個方法我希望打印的名字吧,對不對?但這裏是我所得到的:
a.alpha(); // returns gama ?!?
a.beta(); // returns gama ?!?
a.gama(); // returns gama
但是,當我的課是這樣的:
var ClassB = function() {
this.initialize();
}
ClassB.prototype = {
methods : ['alpha', 'beta', 'gama'],
initialize: function() {
for (var i in this.methods) {
this.addMethod(this.methods[i]);
}
},
addMethod: function(method) {
this[method] = function() {
console.log(method);
}
}
}
var b = new ClassB();
b.alpha(); // returns alpha
b.beta(); // returns beta
b.gama(); // returns gama
這究竟是爲什麼?
是不是通過在JS中的數組循環的[不正確的方式](http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript#answer-3010848)? – PeeHaa 2012-04-02 21:36:48
@RepWhoringPeeHaa - 是的,應該使用plain for循環,但這不是問題。 – nnnnnn 2012-04-02 21:48:47
@nnnnnn我知道這就是爲什麼它是一個評論,而不是一個答案:-) – PeeHaa 2012-04-02 21:51:10