2

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,...

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

2 Comments

hassansin: Thanks, It works,...But it is only on v5.x, and it is not long stable version, production can't use it, 4.x doesn't have this option,...
Yup, not all version have this flag. Depends on which v8 engine it's using.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.