2015-12-15 71 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

感谢您的好解释! –