Featured

First blog post

This is the post excerpt.

Advertisements

This is your very first post. Click the Edit link to modify or delete it, or start a new post. If you like, use this post to tell readers why you started this blog and what you plan to do with it.

post

JavaScript Prototypes

In JavaScript all objects will inherit the methods and properties of a prototype, for example the Car object will inherit from Car.prototype, the Array object will inherit from Array.prototype and the Object will inherit from Object.prototype.

'use strict'

function Car(name, type) {
    this.type = type,
    this.name = name
}

Car.prototype.run = function () {
    console.log(this.type + " " + this.name + " is running");
}

var newKoenigsegg = new Car("Koenigsegg", "Agera");
newcar.run();
Output: Koenigsegg Agera is running

Here the newKoenigsegg instance will inherit from Car.prototypeWhen the newKoenigsegg invokes the run() method the java script engine will look for it in the Car object itself and when it doesn’t find the run() method in the Car object it will move  to it’s prototype (Car.prototype).

Why not define the run() method within the Car object ?

So why did we define the run() method within the  Car.prototype ?, won’t it be much simpler just to define it within the Car object itself ?.

function Car(name, type) {
    this.type = type,
    this.name = name
    this.run = function () {
        console.log(this.type + " " + this.name + " is running");
    }
}

Whenever a Car object is created the run() method which is common to every object will be created with that object and this would create a wastage of resources (memory).

Screenshot (5)

But by defining the run() method within the Car.prototype, the method could be shared between several Car objects, here the Car.prototype will act as a shared object.

Screenshot (7)

Prototype Chaining

The Concept of prototype chaining is for an object’s prototype to have a another prototype and so on.

Screenshot (12).png

function A() {
this.a = "a"
}

function B() {
this.b = "b"
}

function C() {
this.c = "c"
}

var aObj = new A();
B.prototype = aObj;

var bObj = new B();
C.prototype = bObj;

var cObj = new C();

console.log(cObj.b);
console.log(cObj.a);
Output: a and b

Here when value of property is requested the javascript engine looks for it cObj first, then bObj  which is the prototype of and next the aObj the prototype of B.

 

Hope you find this post useful, if you find any mistakes in the post leave them in the comments below.

Have a Nice day and happy coding!