What you are doing is not exactly inheritance, for nothing in your object John
is actually inherited. Javascript heritage is given by means of an internal reference called prototype, that all objects possess. It points to another object, and all properties and methods of the prototype are inherited by the object containing the reference. In the case of Javascript, this is particularly useful for methods.
One of the ways to assign yourself prototype an object is to define the property prototype
of a function, and then invoke it as a manufacturer using the operator new
. The instantiated object will have as prototype the object defined as .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 makes the inheritance. Object.create
receives one object and returns another whose prototype is the object passed. In the above code, this returned object is used as a prototype for all instances of Funcionario
, who therefore inherit the method fazAniversario
. It is worth pointing out that the Object.create
not supported in older browsers like IE8. The link above contains a polyfill which can be used for these browsers to partially support this method.
bfavaretto his explanation on the subject was very constructive, I noticed that in my example above when I used the instanceof command in my reference and in the Employee and People classes in the Employee class he returned true but in the People class he returned false, in his example in both classes instanceof returns true and this is good because I start to see fragments of polymorphism. thank you very much.
– user5545
It’s because now you’re actually creating a chain of prototypes, which is exactly what the
instanceof
check. I’m glad my answer helped :)– bfavaretto
ok, but let’s say the employee has a method called get/set Salary, if you are overwriting the previous object this method will no longer exist, because the mother class does not have the same. Right ?
– Douglas Dreer
@Douglas didn’t understand. Where do I overwrite the previous object? My example uses inheritance.
– bfavaretto