简体   繁体   中英

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

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"

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 Hi, I am a Square. 2420

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM