Is this a correct example of inheritance in JavaScript?

Question:

I'm looking at ways to apply Object Orientation in JavaScript. I found a solution to using inheritance. I wonder if there are better ways and how to encapsulate my classes.

What I've been doing:

People = function(name){
 this.name = name
 this.age = null; 
};

Employee = function(name){
 People.call(this,name);
 this.IdentificationCode = null;
 this.salary = null;
}

Jonh = new Employee("Jonh Smith");
Jonh.age = 25;
Jonh.IdentificationCode = 35632;
Jonh.salary = 3500;

Answer:

What you're doing isn't exactly inheritance, as nothing in your John object is actually inherited. Inheritance in JavaScript is 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 containing the reference. In the case of JavaScript, this is particularly useful for methods.

One way to prototype an object is to define a function's prototype property, and then invoke it as a constructor using the new operator. The instantiated object will have as prototype the object defined as the .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 Object.create line does the inheritance. Object.create takes an object and returns another one whose prototype is the passed object. In the above, the object returned is used as a prototype for all instances of Funcionario , which therefore inherit the method fazAniversario . It's worth pointing out that Object.create is not supported in older browsers like IE8. The link above contains a polyfill that can be used for these browsers to partially support this method.

Scroll to Top