我正试图解决这个谜题头脑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