nagy.zsolt.hun
nagy.zsolt.hun

Reputation: 6694

javascript - refer method before init

Why does "write2" work and "write1" doesn't?

function Stuff() {
    this.write1 = this.method;
    this.write2 = function() {this.method();}
    this.method = function() {
        alert("testmethod");
    }
}
var stuff = new Stuff;
stuff.write1();

Upvotes: 1

Views: 158

Answers (2)

Mike Dinescu
Mike Dinescu

Reputation: 55730

Because the second one evaluates this.method at the time of execution of the anonymous function, while the first makes a reference copy of something that doesn't yet exist.

It can be confusing because it seems like both write1 and write2 attempt to use/reference something that doesn't yet exist but when you declare write2 you are creating a closure which actually only copies a reference to this and then executes the body of the function later, when this has been modified by adding method

Upvotes: 2

kamituel
kamituel

Reputation: 35960

It does not work, because you're referencing this.method before it was declared. Change to:

function Stuff() {

    this.write2 = function() {this.method();}

    // First declare this.method, than this.write1.
    this.method = function() {
        alert("testmethod");
    }
    this.write1 = this.method;
}
var stuff = new Stuff;
stuff.write1();

Upvotes: 1

Related Questions