Javascript es6类构造函数上具有默认参数值的nodejs错误
我运行简单的es6类代码,如下所示:Javascript es6类构造函数上具有默认参数值的nodejs错误,javascript,node.js,function,class,ecmascript-6,Javascript,Node.js,Function,Class,Ecmascript 6,我运行简单的es6类代码,如下所示: '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', thi
'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);
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
它在chrome控制台上运行正常。
但是它在nodejs(4.x,5.x)上运行的错误如下:
'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);
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确实支持函数的默认参数,而且chrome和node.js运行的是V8引擎,为什么要给出不同的答案 这是5.x中正在进行的
功能,可通过标记--harmony\u default\u参数激活该功能:
$ node -v
v5.0.0
$ node --harmony_default_parameters script.js
要查看节点版本中的进行中标志列表,请执行以下操作:
node --v8-options | grep "in progress"
您可以使用Babel
如下方式传输代码:
npm init
npm安装--保存dev babel cli babel-preset-es2015 babel-preset-stage-2
修改package.json
,使其包含以下脚本:
{
“脚本”:{
“开始”:“babel node script.js——预设es2015,第2阶段”
}
}
执行脚本npm run start
。它将输出Hi,我是一个正方形。2420
哈桑森:谢谢,它可以工作,…但是它只在v5.x上,而且不是长期稳定的版本,生产部门不能使用它,4.x没有这个选项,…是的,不是所有的版本都有这个标志。取决于它使用的v8发动机。