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) { = name; = function() {
console.log( + " is running!")

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

var rabbit = new Rabbit('Andy');

var rabbit2 = new Rabbit('Bill');

console.log(rabbit, rabbit2);

No comments:

Post a Comment