Reputation: 267077
I'm trying to write a javascript class which extends from a parent class, overloads one method and changes it slightly.
E.g it checks some variables, if they are set to true, then it executes the same method on parent, otherwise it executes some different code.
This is what I've come up with:
function Dad(name)
{
this.yell = function()
{
console.log( 'GRRRRRRR ' + name);
}
}
function Kid(name, age)
{
var parent = new Dad(name);
parent.yell = function()
{
if (age < 15)
console.log( 'BAAAAA ' + name );
else
parent.yell(); //This is the problem line, how to call this method on
//parent object
}
return parent;
}
var k = new Kid('bob', 13);
k.yell();
However the issue is, how to call the method on the parent object.
Any ideas?
Upvotes: 1
Views: 1271
Reputation: 187034
Use prototypes. They allow you to access the methods of the superclass, but without instantiating it.
Then, from the child class, you can do SuperClass.prototype.instanceMethod.call(this)
, which is basically super
in most typical OO languages, but JS doesn't help you figure out what the superclass is. So you have to keep track of it yourself.
// Superclass
function Dad() {};
Dad.prototype.yell = function() {
console.log("Do your homework!");
}
// Subclass
function Kid(age) {
// calls the constructor of the superclass.
// in this case, the Dad() constructor does nothing, so it's not required here.
Dad.call(this);
// save constructor argument into this instance.
this.age = age;
};
// Inheritance happens here, prototype is an instance of superclass
Kid.prototype = new Dad();
// Make sure the constructor is properly assigned.
Kid.prototype.constructor = Kid;
// Override an instance method.
Kid.prototype.yell = function() {
if (this.age < 18) {
console.log('Waaaaa, I hate homework');
} else {
// calls the yell method of the superclass
Dad.prototype.yell.call(this);
}
}
// make a kid.
var k = new Kid(13);
k.yell(); // 'Waaaaa, I hate homework'
// make an old kid.
var k = new Kid(30);
k.yell(); // 'Do your homework!'
OO inheritance in JS can be messy, but there is some things out there to help.
To name a few.
Upvotes: 2