Friday, May 17, 2024
91
rated 0 times [  92] [ 1]  / answers: 1 / hits: 41433  / 8 Years ago, fri, february 19, 2016, 12:00:00

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



More From » ecmascript-6

 Answers
13

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();

[#63256] Wednesday, February 17, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;