I am trying to solve this cryptic Javascript OOP problem.
So, I have the following class:
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();
When I call each method, I expect to print its name, right? But here is what I get:
a.alpha();
But when my class looks like this:
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();
Why is this happening?
source share