DEV Community

U Prince
U Prince

Posted on

Prototypes in Javascript

Everything is an object in Javascript, well almost.

Functions are also objects in Javascript, albeit a special kind of object.

Eg:

     function sum(a,b) {
        return a+b;
     }
     console.log(typeof sum); // "function"  :)
     Still an object with internal [[call]] method
Enter fullscreen mode Exit fullscreen mode

So, we can do the following on functions:
Eg:

    sum.prop1 = "random property";
    console.log(sum.prop1); // "random property"
Enter fullscreen mode Exit fullscreen mode

Similarly, "prototype" is an inbuilt property on functions in Javascript (except Function function, whose prototype property is a function due to backward compatibility issues).

Note:
"prototype" itself is an object of the said function kind.
Eg:

   console.log(typeof sum.prototype); // "object"
Enter fullscreen mode Exit fullscreen mode

Now, one way to create objects in javascript is using the "new" keyword to call a function (mainly using the constructor functions).

Eg:

    function Person(name, age) {
       this.name = name;
       this.age = age;
    }
    const p1 = new Person("John", 25);
    console.log(typeof p1); // "object"
Enter fullscreen mode Exit fullscreen mode

Now, if you look at the constructor property of the "p1" object and "Person.prototype" object, they'll be equal to the function "Person".

Eg:

    p1.constructor === Person // true
    Person.prototype.constructor === Person // true
Enter fullscreen mode Exit fullscreen mode

This proves that the "prototype" property on a function object refers to the function itself.

Use of Prototypes:
Properties of a function that need to be inherited down the prototype chain are defined inside the "prototype" object. Inheritance in Javascript is possible due to prototypes.

Eg: Let's define a getInfo property on the Person's "prototype" object.

Person.prototype.getInfo = function() {
   return `I am ${this.name}, age ${age}`;
}
const p2 = new Person("Sam", 30);
console.log(p2.getInfo()); // "I am Sam, age 30"
Enter fullscreen mode Exit fullscreen mode

It's possible to access "getInfo" property from "p2" object or any object created from a construction function inheriting Person, because "getInfo" is defined in Person's "prototype" making it an inheritable property down the prototypal chain.

Note: If you are wondering how "p2" object technically has access to the "getInfo" property, it's because if an object does not find a property with itself, it looks for it in its prototype object using the following ways:

p2.__proto__ === Person.prototype 
        // true -- soon to be deprecated, not recommended
Object.getPrototypeOf(p2) === Person.prototype  
        // true -- recommended
Enter fullscreen mode Exit fullscreen mode

Top comments (0)