2016-04-24 71 views
2

我運行簡單的ES6類的代碼如下所示:上ES6類的構造函數錯誤的NodeJS使用默認參數值

'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); 

它是運行Chrome的控制檯就OK了。 但它正在運行,如下的錯誤的NodeJS(4.x中,5.x的):

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 

我覺得ES6的功能做支撐默認參數,和鉻和node.js中都運行V8發動機,爲什麼做給縮小分差的答案,...

回答

3

這是5.x的一個in progress功能,可以通過標誌--harmony_default_parameters被激活:

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

要查看您的節點版本的進步標誌列表:

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

hassansin:謝謝,它的工作原理,...但它僅適用於V5.x中,它是不長的穩定版本,生產不能使用它,4.x的不有這個選項,... – changyh

+0

是的,並非所有的版本都有這個標誌。取決於它使用的是哪個v8引擎。 – hassansin

0

您可以使用Babel來transpile你這樣的代碼:

  1. npm init
  2. npm install --save-dev babel-cli babel-preset-es2015 babel-preset-stage-2
  3. 修改package.json,使其包含以下腳本:

    { 「腳本「:{ 」start「:」babel-node script.js --presets es2015,stage-2 「 } }

  4. 執行腳本npm run start。它將輸出Hi, I am a Square. 2420