我正在努力解决这个难题的
Javascript OOP问题.
所以我有以下课程:
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',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
为什么会这样?