2016-07-05 5 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

Вы должны вызвать для Super constructor.When вызова конструктора базового класса он создает this, а затем вы можете использование this.

class A{ 
    constructor(){ 
     this.name="A"; 
    } 
    M1(){ 
     return "M1"; 
    } 
} 

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

ОБНОВЛЕНО:

Причина, почему вы должны назвать супер-конструктор из производного класса конструктор из-за того, где 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 
    } 
} 

Благодаря Axel Rauschmayer.
Подробнее см. Здесь https://esdiscuss.org/topic/super-on-class-that-extends

+0

Привет, Сурен, не могли бы вы объяснить его более подробно. – user3666112

+0

@ user3666112 обновлен –

+0

Спасибо @Suren за вашу помощь. – user3666112

Смежные вопросы