changyh
changyh

Reputation: 29

nodejs error on es6 class constructor with default parameter value

I am run simple es6 class code as the following:

'use strict';
class Polygon {
  constructor(height=44, width=55) { //class constructor
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }

  sayName() { //class method
    console.log('Hi, I am a', this.name + '.');
   }
}

class Square extends Polygon {
  constructor(length) {
    super(length, length); //call the parent method with super
    this.name = 'Square';
  }

  get area() { //calculated attribute getter
    return this.height * this.width;
  }
}

let s = new Square();

 s.sayName();
 console.log(s.area);

It is running ok on chrome console. But it is running errors on nodejs(4.x, 5.x) as the following:

constructor(height=44, width=55) { //class constructor
                      ^

  SyntaxError: Unexpected token =
  at exports.runInThisContext (vm.js:53:16)
  at Module._compile (module.js:387:25)
  at Object.Module._extensions..js (module.js:422:10)
  at Module.load (module.js:357:32)
  at Function.Module._load (module.js:314:12)
  at Function.Module.runMain (module.js:447:10)
  at startup (node.js:148:18)
  at node.js:405:3

I think es6 do support default parameters for function, and chrome and node.js are run V8 engine, why do give out diff answer,...

Upvotes: 2

Views: 803

Answers (2)

user1341217
user1341217

Reputation:

You can use Babel to transpile your code like this:

  1. npm init
  2. npm install --save-dev babel-cli babel-preset-es2015 babel-preset-stage-2
  3. modify package.json so that it will contain the following script:

    { "scripts": { "start": "babel-node script.js --presets es2015,stage-2" } }

  4. execute the script npm run start. It will output Hi, I am a Square. 2420

Upvotes: 0

hassansin
hassansin

Reputation: 17498

This is an in progress feature in 5.x which can be activated by the flag --harmony_default_parameters:

$ node -v 
v5.0.0
$ node --harmony_default_parameters  script.js

To see a list of in progress flags in your node version:

node --v8-options | grep "in progress"

Upvotes: 3

Related Questions