I'm using one of the approaches to class inheritance in JavaScript (as used in the code I'm modifying), but do not understand how to attach additional functionality for a method in a subclass to the functionality the respective parent class method already has; in other words, I want to override a parent's method in the child class with a method that besides its own sub-class-specific stuff does also the same the parent's method is doing. So, I'm trying to call the parent's method from the child's method, but is it even possible?
The code is here: http://jsfiddle.net/7zMnW/. Please, open the development console to see the output.
Code also here:
function MakeAsSubclass (parent, child)
{
child.prototype = new parent; // No constructor arguments possible at this point.
child.prototype.baseClass = parent.prototype.constructor;
child.prototype.constructor = child;
child.prototype.parent = child.prototype; // For the 2nd way of calling MethodB.
}
function Parent (inVar)
{
var parentVar = inVar;
this.MethodA = function () {console.log("Parent's MethodA sees parent's local variable:", parentVar);};
this.MethodB = function () {console.log("Parent's MethodB doesn't see parent's local variable:", parentVar);};
}
function Child (inVar)
{
Child.prototype.baseClass.apply(this, arguments);
this.MethodB = function ()
{
console.log("Child's method start");
Child.prototype.MethodB.apply(this, arguments); // 1st way
this.parent.MethodB.apply(this, arguments); // 2 2nd way
console.log("Child's method end");
};
}
MakeAsSubclass(Parent, Child);
var child = new Child(7);
child.MethodA();
child.MethodB();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…