I am sure you must have been through the _basics _of JavaScript.By now, you might know that arrays, functions, objects, dates are all _objects._JavaScript is a prototype-based language which means that inheritance works by something called prototypes. Each and every object in JS has a prototype property.

OK, now enough if the fuss about prototypes , let’s understand it.

The usual function constructor approach

As you might be aware of the function constructor approach in JS to create objects so we are going to create a function constructor as such:

var Person = function(name,yearOfBirth,job) {
                      this.name = name;
                      this.yearOfBirth = yearOfBirth;
                      this.job = job;
                      this.calcAge = function(){
                      console.log(2020 - this.yearOfBirth)
                      }
              }

Now, we’ll create two objects Adam and Eve using the Person constructor function:

var Adam = new Person('Adam', 1998, 'teacher');
var Eve = new Person('Eve', 1993, 'painter');

The problem with the above approach is that upon executing the code JS will create two copies each of the properties and methods for the two objects.It isn’t efficient to have two instances of the function calcAge() as storing separate instances of functions for each object ends up wasting memory.Now that’s where prototypes come in.

Prototypes

Every object in JS has a prototype property.This prototype property is an object known as prototype object.It’s the prototype property which makes inheritance easier in JS.

Image for post

Considering the same example if the object Adam wants to inherit a method or a property from the Person object we have to add that method or property to the Person’s prototype property.What is really important to note here is that the Person’s prototype is not the prototype of the Person itself but of all instances that are created through the Person blueprint.So, in this example the Person’s prototype property is the prototype of Adam.

So,the modified Person constructor is as:

var Person = function(name,yearOfBirth,job) {
                      this.name = name;
                      this.yearOfBirth = yearOfBirth;
                      this.job = job;
              }
Person.prototype.calcAge = function(){
                      console.log(2020 - this.yearOfBirth)
                      }

So now when the calcAge() method is called on both the Adam and Eve objects:

Adam.calcAge(); //22
Eve.calcAge(); //27

Now you can observe that while the method calcAge() is not directly in the Person object but we can still access it because it is in the prototype property of the Person function constructor.

#prototype-chain #javascript #prototype #programming

Understanding Prototypes in JavaScript
1.60 GEEK