Прототипное наследование, переопределение метода родителя
Подскажите пожалуйста, имеются два конструктора, в прототипах которых определены методы calc. Вопрос заключается вот в чем: в прототипном методе calc (ClassB.prototype.calc) для переопределения метода вызывается метод родителя calc (ClassA.prototype.calc.apply(this)), как можно вызвать этот метод не зная имени родителя?
function ClassA(a, b) { this.a = a; this.b = b; this.c = 1; return this.a + this.b + this.c; } ClassA.prototype.calc = function() { return this.a + this.b + this.c; } let class1 = new ClassA(2, 2); function ClassB(d, f) { this.d = d; this.e = f; this.f = 10; ClassA.apply(this, arguments); } ClassB.prototype = Object.create(ClassA.prototype); ClassB.prototype.constructor = ClassB; ClassB.prototype.calc = function() { var jas = ClassA.prototype.calc.apply(this); return jas + this.d + this.e + this.f; } let class2 = new ClassB(20, 20); console.log(class1.calc()); console.log(class2.calc()); |
В 25 строке поменяйте на...
var jas = this.__proto__.__proto__.calc.apply(this); |
Лучше для этого использовать ключевое слово super, но оно работает только внутри специального синтаксиса для класса
class ClassA { constructor(a, b) { this.a = a; this.b = b; this.c = 1; return this.a + this.b + this.c; } calc() { return this.a + this.b + this.c; } } let class1 = new ClassA(2, 2); class ClassB extends ClassA { constructor(d, f) { super(...arguments); this.d = d; this.e = f; this.f = 10; } calc() { var jas = super.calc(); return jas + this.d + this.e + this.f; } } let class2 = new ClassB(20, 20); console.log(class1.calc()); console.log(class2.calc()); |
Можно префикс одинаковый делать
function superize(Child, prefix) { var p1 = Child.prototype, p2 = p1.__proto__; if (p2) { p1[prefix + 'constructor'] = p2.constructor; for (var p in p2) { if (p1.hasOwnProperty(p) && typeof p2[p] == 'function') { p1[prefix + p] = p2[p]; } } } } function ClassA() {} ClassA.prototype.calc = function () {}; function ClassB() { this.ClassA_constructor(); } ClassB.prototype = Object.create(ClassA.prototype); ClassB.prototype.constructor = ClassB; ClassB.prototype.calc = function () { this.ClassA_calc(); }; superize(ClassB, 'ClassA_'); console.log(new ClassB); |
Часовой пояс GMT +3, время: 16:21. |