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
Calling a Constructor You call a constructor when you create a new instance of the class containing the constructor. Here is a Java constructor call example: MyClass myClassVar = new MyClass(); This example invokes (calls) the no-argument constructor for MyClass as defined earlier in this text.
You shouldn't: calling instance method in constructor is dangerous because the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on testability.
No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With