Search code examples
javascriptinheritanceprototypal-inheritance

Javascript prototypal Inheritence


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

    this.sayName = function () {
        console.log("My Name is "+ this.name);
    }
}

var nitin = new Person("Nitin");

nitin.sayName(); // My Name is Nitin


// Codebreak

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

Person.prototype.sayName = function (){
  console.log("My Name is "+ this.name);
}

var nitin = new Person("Nitin");

nitin.sayName(); // My Name is Nitin

I was going though inheritance in JS, but for both the approaches above result is same. So I am confused here which approach to follow and why?


Solution

  • The former has an empty prototype consisting only of the constructor function. The latter has a prototype with a behavior (sayName).

    There is no possibility to inheriting behavior from the first example, as it has no prototype, whereas in the second example, the prototype can be passed on and thus inherited from.

    Moreover, from a memory management / code execution standpoint, the prototype is more efficient. V8 (Google's JavaScript interpreter), and most other JS interpreters, will construct reusable code from prototypes when interpreting them. This both saves space from not needing multiple different functions, as well as speed from not needing to construct them each time the need arises.