2013-03-11 39 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