JavaScript Changing class method from outside | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

JavaScript Changing class method from outside

Is it possible in JavaScript to change a method of a class from outside? Example: class Sub { constructor (num) { this.num = num; } substraction(n) { return this.num - n; } } can I add, for example, console.log() to every call of substraction() without changing class Sub?

30th Jun 2020, 1:00 PM
Nika Nika
1 Answer
+ 3
You can extend the class and override the method. There are other ways, but IMO this is the most straight forward and easy to understand. class Sub { constructor(num) { this.num = num; } subtraction(n) { return this.num - n; } } class Sub2 extends Sub { subtraction(n) { console.log(this.num - n); } } let sub = new Sub2(6); sub.subtraction(4); // outputs 2 in the console
30th Jun 2020, 5:25 PM
ChaoticDawg
ChaoticDawg - avatar