31
votes

I'm getting an error when calling a class method from its constructor. Is it possible to call a method from the constructor? I tried calling the base class method from the constructor of a derived class but I am still getting an error.

'use strict';

class Base {
    constructor() {
        this.val = 10;
        init();
    }

    init() {
        console.log('this.val = ' + this.val);
    }
};

class Derived extends Base {
    constructor() {
        super();
    }
};

var d = new Derived();

➜ js_programs node class1.js /media/vi/DATA/programs/web/js/js_programs/class1.js:7 init(); ^

ReferenceError: init is not defined at Derived.Base (/media/vi/DATA/programs/web/js/js_programs/class1.js:7:9) at Derived (/media/vi/DATA/programs/web/js/js_programs/class1.js:18:14) at Object. (/media/vi/DATA/programs/web/js/js_programs/class1.js:23:9) at Module._compile (module.js:435:26) at Object.Module._extensions..js (module.js:442:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:311:12) at Function.Module.runMain (module.js:467:10) at startup (node.js:136:18) at node.js:963:3 ➜ js_programs

2
Maybe the title should be Calling a method from constructor or Calling a member function from constructor. A class method is a static method. - DarkTrick

2 Answers

42
votes

You're calling the function init(), not the method init of either Base or the current object. No such function exists in the current scope or any parent scopes. You need to refer to your object:

this.init();
11
votes

You are missing this keyword:

this.init();