2013-03-11 62 views
1

为什么“write2”工作,“write1”不工作?javascript - 参考init之前的方法

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

回答

2

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

它可以是混乱,因为它看起来既write1write2尝试使用/参考的东西,还不存在,但是当你声明write2你正在创建一个闭合实际上只复制到this的引用,然后执行函数体的后来,当this已被修改时加入method

1

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

以及为什么参考在write2中工作? – 2013-03-11 13:29:32

+0

因为'write2'中的''this.method()'的引用在'write2()'调用时被评估,此时'this.method'已被定义。 – kamituel 2013-03-11 13:31:44