What you're doing is not exactly inheritance, because nothing in your John
object is actually inherited. Inheritance in JavaScript occurs through an internal reference called prototype , which all objects have. It points to another object, and all properties and methods of the prototype are inherited by the object that contains the reference. In the case of JavaScript, this is particularly useful for methods.
One way to assign prototype to an object is to set the prototype
property of a function, and then invoke it as constructor using the new
operator. The instantiated object will have prototype the object set to .prototype
of the constructor. For example:
// Define "classe" Pessoa
function Pessoa(nome, idade) {
this.nome = nome;
this.idade = idade;
}
// Toda pessoa tem uma método fazAniversário
Pessoa.prototype.fazAniversario = function() {
this.idade++;
}
// Define classe Funcionario
function Funcionario(nome, idade) {
Pessoa.call(this, nome, idade);
this.salario = null;
}
// Todo funcionário herda de Pessoa
Funcionario.prototype = Object.create(Pessoa.prototype);
// Teste
var joao = new Funcionario('João', 25);
joao.fazAniversario();
alert(joao.idade); // 26
The line of Object.create
is what it does the inheritance. Object.create
receives an object and returns another whose prototype is the last object. In the code above, this returned object is used as the prototype of all instances of Funcionario
, which is why they inherit the fazAniversario
method. It is worth noting that Object.create
is not supported in older browsers like IE8. The above link contains a polyfill that can be used for these browsers to partially support this method.