javascript-在初始化之前引用方法
为什么“write2”有效而“write1”无效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.
它不起作用,因为您在声明它之前引用了
此.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();