Sto provando a risolvere questo problema OOP JavaScript Javascript.Classi Javascript e riferimenti variabili
così ho la seguente classe:
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();
Quando chiamo ogni metodo mi aspetto di stampare il nome di essa, giusto? Ma qui è ciò che ottengo:
a.alpha(); // returns gama ?!?
a.beta(); // returns gama ?!?
a.gama(); // returns gama
Ma quando la mia classe è simile al seguente:
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
perché sta succedendo questo?
Non è [il modo errato] (http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript#answer-3010848) di eseguire il looping di un array in JS? – PeeHaa
@RepWhoringPeeHaa - Sì, dovrebbe essere usato un ciclo for for, ma non è questo il problema. – nnnnnn
@nnnnnn So che è per questo che è un commento e non una risposta :-) – PeeHaa