Overriding methods means method overwriting and is a technique of object-oriented programming. This technique consists of overriding methods that have been inherited to add extra code or simply change / extend its functionality.
Imagine that we have the function Hero
:
Hero
function Hero () {
this.name = '';
}
Hero.prototype.getPowers = function() {
return ['Super strength'];
}
Hero.prototype.toString = function() {
var str = 'Hello, I\'m a superhero and my name is ' + this.name;
str += '\nThis are my powers:\n\n'
for(var power of this.getPowers()) {
str += '- ' + power + '\n';
}
return str;
}
As you can see, the function Hero
has a property name
and two methods: getPowers
and hello
. The method getPowers
returns the list of powers of the hero and toString
returns a toString
(inherited from Object
) custom of the object, showing its name and its powers.
Now, we have a function called Superman
:
Superman
function Superman() {
this.name = 'Clark Kent';
}
Superman.prototype = new Hero();
Superman.prototype.getPowers = function() {
var powers = Hero.prototype.getPowers();
powers.push('X-ray vision');
powers.push('Fly');
powers.push('Extreme velocity');
return powers;
}
The first thing we notice when looking at the function Superman
is that it inherits from Hero
. We can find this on the line:
Superman.prototype = new Hero();
Below we see that we have redefined the method getPowers
. This method is said to be overwritten , since it overwrites the original method of Hero
. In this overwritten method we have extended its functionality in order to add Superman's own powers.
If we execute the previous code, we will see that it lists all the powers of Superman
and not only the Hero
.
Complete example
function Hero () {
this.name = '';
}
Hero.prototype.getPowers = function() {
return ['Super strength'];
}
Hero.prototype.toString = function() {
var str = 'Hello, I\'m a superhero and my name is ' + this.name + '. ';
str += 'These are my powers:\n\n'
for(var power of this.getPowers()) {
str += '- ' + power + '\n';
}
return str;
}
function Superman() {
this.name = 'Clark Kent';
}
Superman.prototype = new Hero();
Superman.prototype.getPowers = function() {
var powers = Hero.prototype.getPowers();
powers.push('X-ray vision');
powers.push('Fly');
powers.push('Extreme velocity');
return powers;
}
var clark = new Superman();
console.log(clark.toString());