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

时间:2017-05-09 05:11:15

标签: javascript es6-class

我对es6很新。下面是我的简单Student类,其中一个构造函数接受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。我发现它不适用于构造函数。

1 个答案:

答案 0 :(得分:0)

因为构造函数方法是初始化用javascript中的类创建的对象 - 如果你试图在构造函数本身的函数参数中访问它,this将始终是一个空对象。

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