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?
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