1

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

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

2 回答 2

2

因为第二个this.method在执行匿名函数时进行评估,而第一个创建了一个尚不存在的东西的参考副本。

这可能会让人感到困惑,因为它似乎都write1试图write2使用/引用尚不存在的东西,但是当你声明write2你正在创建一个实际上只复制一个引用this然后执行函数体的闭包时,当this有通过添加修改method

于 2013-03-11T12:52:56.883 回答
1

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();
于 2013-03-11T12:50:08.413 回答