Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'super' outside of function or class

I can't transpile this little piece of code:

class FooBar extends SomeParent {

  constructor() {
    super();
  }

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

The error thrown is 'super' outside of function or class .

However, the same code transpiles fine in Babel REPL.

I'm transpiling using a custom Node.JS program using this command:

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

Installation info:

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

$ node -v
v0.10.40

What am I doing wrong? I had no problems when transpiling using Babel 5...

like image 632
Udo G Avatar asked Dec 15 '15 13:12

Udo G


1 Answers

It works in the Babel REPL because Babel 5 did not have checks for this I'd assume.

This is not valid:

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

But using an arrow function does:

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

because super behavior is based on the this environment of its calling location. While an arrow function shares its this environment with its parent, a standard function introduces a whole not this environment.

Specifically:

  1. 12.3.5.1 calls MakeSuperPropertyReference()
  2. 12.3.5.3 calls GetThisEnvironment() which in the first case will be the function expression, and in the arrow case will be the class method, and then calls HasSuperBinding() in that environment.
  3. 8.1.1.3.3 will return false in the first case because function expressions do not have a [[HomeObject]] whereas class methods do.
like image 166
loganfsmyth Avatar answered Sep 25 '22 15:09

loganfsmyth