在构造函数中分配默认值时出现 ES6 类型错误

ES6 type error when assigning default values in constructor

我对 es6 很陌生。下面是我的简单 Student class 构造函数接受 2 个参数。当未传递参数时,我通过在构造函数签名本身中调用函数来分配默认值。

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

这是导致以下错误的结果:

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;
    }

更新: 启动默认值的相同方法适用于函数。检查上面的 setRegNosetName。我观察到它不适用于构造函数。

因为构造函数方法是初始化在 javascript 中使用 class 创建的对象的方式 - 如果您尝试在构造函数本身的函数参数。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions

class Foo {
    constructor(foo = () => console.log(this), bar = () => console.log('baz')) {
      foo(); // {}
      bar(); // baz
    }
}

const foo = new Foo();

https://repl.it/HnjB/2