在init之前引用方法

refer method before init

本文关键字:引用 方法 init      更新时间:2023-09-26

为什么"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的值,而第一个函数对一个还不存在的东西做了一个引用副本。

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

它不起作用,因为您在声明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();