Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a class method from the constructor

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

like image 715
Vivek Kumar Avatar asked Feb 19 '16 11:02

Vivek Kumar


People also ask

How do you call a class in a constructor?

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.

Is it bad to call a method in the constructor?

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.

Can we call another method from constructor in Java?

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.


1 Answers

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(); 
like image 59
deceze Avatar answered Oct 14 '22 14:10

deceze