2015-12-15 70 views
7

之外,我不能transpile這小小的一段代碼:「超級」的功能或

class FooBar extends SomeParent { 

    constructor() { 
    super(); 
    } 

    start() { 
    var foo = function() { 
     super.start();  // <-- Error: 'super' outside of function or class 
    }; 
    } 
} 

拋出的錯誤是'super' outside of function or class

但是,相同的代碼在Babel REPL中轉換正常。

我使用的這個命令的自定義Node.js的程序transpiling:

babel.transformFileSync(filename, { presets: [ 'es2015' ] }); 

安裝信息:

$ npm ls --global --depth 0 
/usr/lib 
├── [email protected]13 
├── [email protected] 
├── [email protected] 
├── [email protected] 
├── [email protected] 
├── [email protected] 
├── [email protected] 
├── [email protected] 
├── [email protected] 
└── [email protected] 

$ node -v 
v0.10.40 

我在做什麼錯?當使用Babel 5進行運輸時,我沒有任何問題...

+0

可能是因爲REPL使用了babel 5而您使用的是babel 6? – Jivings

+4

使用箭頭函數而不是常規函數,這將確保'super'來自父範圍。我不確定究竟哪個實現是正確的,但是我會猜測* Babel 6,因爲在類之外訪問'super' – CodingIntrigue

+0

請參閱[「應該在其標題中包含」標籤「? 「](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles),其中的共識是」不,他們不應該「! –

回答

4

它在Babel REPL中起作用,因爲Babel 5沒有檢查我想要的。

這是無效的:

class Example extends Parent { 
    start() { 
    var foo = function() { 
     super.start(); 
    }; 
    } 
} 

但用箭頭功能的作用:

class Example extends Parent { 
    start() { 
    var foo =() => { 
     super.start(); 
    }; 
    } 
} 

因爲super行爲是基於this環境的調用位置。雖然箭頭函數與其父項共享其this環境,但標準函數會引入整個而不是this環境。

具體來說:

  1. 12.3.5.1呼叫MakeSuperPropertyReference()
  2. 12.3.5.3呼叫GetThisEnvironment()其中在第一種情況下將函數表達式,並且在箭頭情況下將是類方法,然後在該環境中調用HasSuperBinding()
  3. 8.1.1.3.3在第一種情況下將返回false,因爲函數表達式沒有[[HomeObject]],而類方法有。
+0

感謝您的好解釋! –