ES6:'this'在继承的类中未定义

Jas*_*bas 1 node.js ecmascript-6

我有两个班,分别是A和B. 类定义如下所示.

class A {

    constructor(){
        ...
    }

    ...
}

//Implementation 1

class B extends A {
    constructor(){
        this.childProperty = "something"; // this is undefined.
    }
}

//Implementation 2

class B {
    constructor(){
        this.childProperty = "something"; // this is not undefined.
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么this未定义Implementation 1而不是Implementation 2?我在这做错了什么?

Die*_*erg 14

你需要先打电话super():

class B extends A {
   constructor() {
     super();
     this.childProperty = "cool"
   }
}
Run Code Online (Sandbox Code Playgroud)

的jsfiddle


Nad*_*bit 5

尝试将super添加到您的班级:

class B extends A {
    constructor(){
        super()
        this.childProperty = "something"; 
    }
}
Run Code Online (Sandbox Code Playgroud)