2016-07-05 70 views
2
class A{ 
    constructor(){ 
     this.name="A"; 
    } 
    M1(){ 
     return "M1"; 
    } 
} 

class B extends A{ 
    constructor(){ 
     this.id="B"; 
    } 
    M2(){ 
     return "M2"; 
    } 
} 

var b = new B(); 

输出:在创建类的对象时,它抛出一个错误

ReferenceError: this is not defined at B (repl:4:1) at repl:1:9 at REPLServer.defaultEval (repl.js:262:27) at bound (domain.js:287:14) at REPLServer.runBound [as eval] (domain.js:300:12) at REPLServer. (repl.js:431:12) at emitOne (events.js:82:20) at REPLServer.emit (events.js:169:7) at REPLServer.Interface._onLine (readline.js:211:10) at REPLServer.Interface._line (readline.js:550:8)

回答

5

必须调用超强的 constructor.When调用基类构造函数它创建this,然后你可以使用this

​​

更新:

为什么你需要调用派生类的构造函数的超级构造函数的原因是由于其中ES6分配情况 - 它们是由/基类(该分配是必要的,这样的构造可以被子类具有异国情调的情况下,如阵列):

// Base class 
class A { 
    // Allocate instance here (done by JS engine) 
    constructor() {} 
} 
// Derived class 
class B extends A { 
    constructor() { 
     // no `this` available, yet 
     super(); // receive instance from A 
     // can use `this` now 
    } 
} 
// Derived class 
class C extends B { 
    constructor() { 
     // no `this` available, yet 
     super(); // receive instance from B 
     // can use `this` now 
    } 
} 

由于阿克塞尔Rauschmayer先生
欲了解更多信息,请点击这里https://esdiscuss.org/topic/super-on-class-that-extends

+0

嗨Suren,你能不能请解释一下。 – user3666112

+0

@ user3666112已更新 –

+0

谢谢@Suren的帮助。 – user3666112

相关问题