javascript-在初始化之前引用方法

javascript-在初始化之前引用方法,javascript,init,Javascript,Init,为什么“write2”有效而“write1”无效 它不起作用,因为您在声明它之前引用了此.method。改为: function Stuff() { this.write2 = function() {this.method();} // First declare this.method, than this.write1. this.method = function() { alert("testmethod"); } this.

为什么“write2”有效而“write1”无效


它不起作用,因为您在声明它之前引用了
此.method
。改为:

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();

因为第二个方法在执行匿名函数时计算
this.method
,而第一个方法生成一个尚不存在的引用副本


这可能会让人困惑,因为
write1
write2
似乎都试图使用/引用尚不存在的东西,但当您声明
write2
时,您正在创建一个闭包,实际上它只复制了对
的引用,然后稍后执行函数体,当
通过添加
方法修改此
时,因为在
write2
中,对
此.method()
的引用在调用
write2()
时计算,此时已定义了
此.method
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();