Search code examples
javascriptclassecmascript-6extendsprototypal-inheritance

javascript: call base class function


I have the following code, and I am trying to inherit from a base class. Why does the code say that identify() is not defined? Shouldn't it call the function from the base class?

Error: ReferenceError: identify is not defined source1.js:23:9

class TestBase {
    constructor() {
        this.type  = "TestBase";
    }

    run() {
        console.log("TestBase Run");
    }

    identify() {
        console.log("Identify:" + this.type);
    }
}

class DerivedBase extends TestBase {
    constructor() {
        super();
        this.type  = "DerivedBase";
    }

    run() {
        console.log("DerivedBase Run");
        identify();
    }
}

window.onload = function() {
  let derived = new DerivedBase();
  derived.run();
}

Solution

  • You must call this.identify() instead.

    For more information you can read about classes in general.

    Please take into account that classes in javascript are just a syntactic sugar on top of prototypal inheritance.