我正在努力解决这个难题的
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
为什么会这样?
解决方法
for ( var i in this.methods ) { this[this.methods[i]] = function() { console.log(this.methods[i]); } }
你的问题就在这里.当这个循环结束时,我是最后一个元素.每个函数使用相同的i,因此它们都是最后一个元素.
当您使用addMethod时,您正在创建一个“捕获”正确值的闭包.
编辑:当您调用addMethod时,您正在“复制”该值,而不是使用i值,该值随每次循环迭代而变化.