Javascript – Is doing Parent.call from the child object a right way to implement Inheritance in JavaScript

inheritancejavascript

I came across this piece of code. It didn't look that right to me. Is this the right way to implement super in JavaScript? If not, what is the right way?

function Person(name){
  this.name = name;  
}

function Student(name){
  Person.call(this, name);
}

Student.prototype = new Person(); 
var a = new Student('test');
var b = new Student('test2');

Best Answer

This works and is the right way depending on whether or not the browser supports Object.create:

Student.prototype = Object.create(Person.prototype);

The Object.create method sets up prototypal inheritance without executing the constructor function Person when "inheriting."

Related Topic