Как переопределить метод класса (не через экземпляр)

const startedNumber = new Addition(5);
const result = startedNumber .add(3,5,6) //В консоль выводится "called"
console.log(result) //В консоль выводится 19

class Addition {
constructor (num) {
    this.num = num;
}

add (...nums) {
    const sum = (a, b) => a + b;
    return this.num + nums.reduce(sum);
}

}

**// Write you code here 
// Я здесь тупо скопировал метод 
Addition.prototype.add =  function(...num) {
console.log('called');
const sum = (a, b) => a + b;
return this.num + num.reduce(sum)
};
// End of code**

Ответы (1 шт):

Автор решения: vsemozhebuty

По вашему вопросу трудно понять, что именно требуется. Рискну предположить, что вам нужно переопределить метод, не зная его содержимое, то есть что-то добавить к нему, а потом вызвать оригинальный метод. Можно так:

class Addition {
  constructor(num) {
    this.num = num;
  }

  add(...nums) {
    const sum = (a, b) => a + b;
    return this.num + nums.reduce(sum);
  }
}

const original = Addition.prototype.add;

Addition.prototype.add = function addRedefined(...num) {
  console.log('called');
  return original.call(this, ...num);
};

const startedNumber = new Addition(5);
const result = startedNumber.add(3, 5, 6); // В консоль выводится "called"
console.log(result); // В консоль выводится 19

→ Ссылка