简体   繁体   English

创建类的对象时,将引发错误

[英]While creating object of class, it throws an error

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

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

var b = new B();

output: 输出:

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. ReferenceError:未在REPLServer.runBound的边界(domain.js:287:14)的REPLServer.defaultEval(repl.js:262:27)的repl:1:9的B(repl:4:1)处定义[作为评估](domain.js:300:12)。 (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) (repl.js:431:12)位于REPLServer.emit(events.js:169:7)位于ELPLServer.Interface._onLine(readline.js:211:10)处于emitOne(events.js:169:7) .Interface._line(readline.js:550:8)

You must call super's constructor.When you call the base class constructor it creates the this and then you can use this . 您必须调用super的构造函数。调用基类构造函数时,它会创建this ,然后可以使用this

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

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

UPDATED: 更新:

The reason why you need to call the super-constructor from a derived class constructor is due to where ES6 allocates instances – they are allocated by/in the base class (this is necessary so that constructors can be subclassed that have exotic instances, eg Array): 您需要从派生类构造函数调用超级构造函数的原因是ES6分配实例的位置–它们是由基类/在基类中分配的(这是必需的,以便可以将具有异类实例的构造函数子类化,例如Array。 ):

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

Thanks to Axel Rauschmayer . 感谢Axel Rauschmayer
For more see here https://esdiscuss.org/topic/super-on-class-that-extends 有关更多信息,请参见此处https://esdiscuss.org/topic/super-on-class-that-extends

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM