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?
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 basicallysuperin 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.OO inheritance in JS can be messy, but there is some things out there to help.
To name a few.