Javascript classes and variable references
<p>I'm trying to solve this puzzle minded Javascript OOP problem.</p>

<p>So I have the following class :</p>

<pre><code>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();
</code></pre>

<p>When I call every method I expect to print the name of it, right? But here is what i get :</p>

<pre><code>a.alpha(); // returns gama ?!?
a.beta();  // returns gama ?!?
a.gama();  // returns gama
</code></pre>

<p>But when my class looks like this :</p>

<pre><code>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
</code></pre>

<p>Why is this happening ?</p>
