Menu

Objects in JavaScript

JavaScript is called as Class-less Object Oriented Language(some says Object Based Language), because in javascript there is no concept of classes , still we have Objects.Functions can be used to somewhat simulate classes, but in general JavaScript is a class-less language.

Out of the three basic properties of a object orient language i.e Encapsulation,Inheritance and Polymorphism, Javascript
supports Encapsulation and Inheritance(though it supports polymorphism, but it is unnecessary to do this in JavaScript, and the result is usually complex code that is not always productive ). Everything in javascript is an object – classes are objects, functions are objects, numbers are objects,objects are objects.

So we have just created a object in javascript named pointObj having two properties x and y and a method named getCoordinates(). Normally literal notation is preferred if we are using this object as a single object and not requiring
more than one instance of the object.

So here we have created two pointObj using a constructor function and this method is preferable when we require multiple instances of the object where each instance can be changed during the lifetime of the script.

Note: JavaScript also provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.

In JavaScript, each Object can inherit properties from another object, called it’s prototype. When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object’s prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype.

Why to use prototype?
In all of the above example, you may notice that I have defined the methods inside the object, this means the method getCoordinates() is recreated every time we create a new object. So if we will create 100 points , then each point will contain their own copy of getCoordinates() method.
A more inexpensive way is to add getCoordinates() method to the prototype of the constructor function.
Ex:

Now the same method will be shared between all the objects and will take less memory.So we should always consider defining the methods on the prototype of the object. Now if we will create an instance of Point object,

var pointObj = new Point(5,6);

the pointObj will contain a property named ‘__proto__’ which will point to Point.prototype as Point is the constructor of our new instance.