A bit about Javascript's prototype chain

Photo by Jess Bailey on Unsplash

A bit about Javascript's prototype chain

·

3 min read

Javascript objects have an internal property called prototype, which is simply a reference to another object and that object also has prototype property which may point to null or another object. This is called Prototype chain in javascript.

var myObject= {
    name: "objName",
    getName: function () {
        return this.name
    }
}
console.log(myObject.getName()) //objName

Here myObject has name as property and getName as method . In the browser console if you type myObject followed by a . you will see many other properties and methods, these extra properties comes from the object referenced by prototype .

Note: The property referencing that linked object is not called prototype. In all major browser it is implemented as __proto__ . A standard way to get prototype of an object is to use Object.getPrototypeOf() method.

Now if we call hasOwnProperty("name") on myObject as myObject.hasOwnProperty("name"), first browser will check whether hasOwnProperty exist in myObject or not, but as it does not exist so it will check on the prototype object of myObject. After finding the property on prototype linked object, hasOwnProperty is called.

var anotherObject = {
    a: 2
};

// create an object linked to `anotherObject`
var myObject = Object.create( anotherObject );

myObject.a; // 2

Object.create( anotherObject ) will create a new object that is prototype linked to the anotherObject . So now we have myObject prototype linked to anotherObject , which is prototype linked to Object.prototype , which is again prototype linked to null.

Note: Object.prototype is the top level object. This is the end of every prototype chain. It includes many useful utilities like toString() and valueOf() etc.

constructor

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

Fun.prototype.getName= function() {
    return this.name;
};

var a = new Fun( "a" );
var b = new Fun( "b" );

a.getName(); // "a"
b.getName(); // "b"

Here Fun is used as a constructor. new Fun() is the constructor call. This will create a new object, assign properties to that object as defined by Fun's body, then set Fun.prototype as the prototype of the new object. Now any object created by Fun will have property name and will be able to access method getName .

a --> Fun.prototype --> Object.prototype --> null

Summary

  1. When attempting to access a property in an object , it's prototype linkage decides where to look next for the property if it is not found on the object.
  2. Every object in Javascript has Object.prototype as top level object at the end of prototype chain. Object.prototype has the common utilities that all the objects can access to .
  3. Creating object using new keyword followed by a function and defining methods in Function.prototype we can simulate inheritance.