对于es6
我很新。以下是我的简单Student
类与接受2个参数的构造函数。我通过在构造函数签名本身中调用函数来分配默认值,当参数未被传递时。在构造函数中分配默认值时出现ES6类型错误
index.js:9Uncaught TypeError: this.defaultRno is not a function
at new Student (index.js:9)
at Object.<anonymous> (index.js:21)
at __webpack_require__ (bootstrap f01272b…:555)
当我更改类似下面的构造,是没有看到错误:
constructor(regNo = -1, name = 'unknown') {
this.regNo = regNo;
this.name = name;
}
UPDATE: 开始以同样的方式
class Student {
defaultRno =() => -1;
defaultName =() => "unknown";
/**
* The default constructor
*/
constructor(regNo = this.defaultRno(), name = this.defaultName()) {
this.regNo = regNo;
this.name = name;
}
setRegNo = (rno = this.defaultRno()) => this.regNo = rno;
setName = (name = this.defaultName()) => this.name = name;
displayConsole =() => console.log(`Reg.No# ${this.regNo}\nName: ${this.name}`);
}
// create student object
var stu = new Student();
stu.displayConsole();
这与下面的错误导致默认值与函数一起使用。上面检查setRegNo
和setName
。我发现它不适用于构造函数。
在参数给构造进行评价时,缺省应用,该对象不完全构造,并且仍然缺少像'defaultRno'方法。有没有理由不能只写'constructor(regNo = -1,name =“unknown”)'? – 2017-05-09 05:20:37
这不是ES6。您正在使用实验性的转换器插件,并且您不明白类字段语法的作用。 – Bergi
类体中的箭头函数不会按照您想要的方式工作。但是,您可以使用简写方法声明,如'setRegNo(){}'。 – Marty