JavaScript inheritance overwriting and calling class functions


If you want to inherit a class and then overwrite parts of it with new code, but still keep the original then you will need to use the call and apply functions in the correct order.

1) call the parent class first
2) save a reference to the original function first
3) apply the arguments of the new function back to the parent class function

Here's a working example.

function Animal(name) {
this.name = name;
this.run = function() {
console.log(this.name + " is running!")
}
}

function Rabbit(name) {
Animal.call(this, name); // call the parent constructor first to bring in the class 
var parentRun = this.run; // save a reference to the old run function
this.run = function() { // overwrite with a new run function
parentRun.apply(this); // call the previous run function
console.log(this.name + " is running 2!");
}
this.bounce = function() { // add a new class function
console.log(this.name+" is bouncing");
}
}
Rabbit.prototype = new Animal(); // this allows you to see the chain of prototypes in console log

var rabbit = new Rabbit('Andy');
rabbit.bounce();
rabbit.run();

var rabbit2 = new Rabbit('Bill');
rabbit2.bounce();
rabbit2.run();

console.log(rabbit, rabbit2);

No comments:

Post a Comment