为什么“write2”有效而“write1”无效?
function Stuff() {
this.write1 = this.method;
this.write2 = function() {this.method();}
this.method = function() {
alert("testmethod");
}
}
var stuff = new Stuff;
stuff.write1();
为什么“write2”有效而“write1”无效?
function Stuff() {
this.write1 = this.method;
this.write2 = function() {this.method();}
this.method = function() {
alert("testmethod");
}
}
var stuff = new Stuff;
stuff.write1();
因为第二个this.method
在执行匿名函数时进行评估,而第一个创建了一个尚不存在的东西的参考副本。
这可能会让人感到困惑,因为它似乎都write1
试图write2
使用/引用尚不存在的东西,但是当你声明write2
你正在创建一个实际上只复制一个引用this
然后执行函数体的闭包时,当this
有通过添加修改method
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();