2014-03-25 20 views
0

我們使用tsc.exe將.ts文件編譯到各自的.js文件中。由於某些原因,TypeScript編譯器將var _this = this;添加爲生成文件的第一行。爲什麼tsc.exe(TypeScript編譯器)添加var _this = this;作爲輸出js文件的第一行?

例如:

declare var define; 
define({ 
}); 

被編譯成

var _this = this; 
define({ 
}); 

編譯器與ARGS文件這樣調用:

--comments --module AMD --target ES5 
"c:\abc\Scripts\Framework\Modules\Store\TreeStoreMixin.ts" "c:\abc\Scripts\Framework\Client\AppBulletin.ts" ... 

(該文件被截斷爲起見簡潔)

爲什麼?我會理解,如果this是指一個外部函數,所以_this將捕獲其範圍。但這是一個全局文件級別的範圍,不是嗎? this在這裏沒有用。我可以指示編譯器不生成它嗎?

+0

您使用的是哪種版本的編譯器?國旗現在還沒有被「 - 評論」一段時間。 –

+0

版本0.8.3.1 – mark

+0

編譯器中的錯誤。強烈建議升級到0.9.7(1.0 Release Candidate)。 –

回答

0

在編譯器的最新版本,你的代碼編譯爲:

define({}); 

你會發現在編譯器的最新版本的輸出有效利用_this,但只有在你使用的脂肪箭頭語法,例如...

class Example { 
    constructor(public name: string) { 

    } 

    // _this variable will be defined before here 
    public eventHandler =() =>{  
     // will be _this.name in output 
     alert(this.name); 
    } 
} 

var example = new Example('mark'); 

window.setTimeout(example.eventHandler, 1000); 

我懷疑有在你使用的是錯誤的產生_this變量時實際上並不需要它老版本編譯程序的錯誤。

+0

不幸的是,我無法升級 - 舊版本和新版本之間存在太多不兼容的情況。目前超出我的授權範圍。 – mark

相關問題