Wednesday, July 8, 2015

Javascript Create Objects in Different ways.

Object Literals

In javascript we can create a object using object literals.
To store data we can define properties. In here I have showed four different ways to define properties.

Using Object.create

Another way to create objects in javascript is using Object.Create. Advantage is, it will allows to create objects which based upon other objects.
Now we will create objects which based on another object.
In above code, myBentleyCar's prototype is bentleyCar. We can verify that using following code.

Constructor functions

Another way to create objects in javascript is using constructor functions. In here name of the function should be begins with upper case letter, Then we can easily identify a constructor with other javascript functions. We can pass parameters using following way.
Then we define a method in this object. But reality is a property which contains a function object. But logically we could describe it as a method.
Using instanceof keyword we can determine whether an object is a instance of particular constructor.
The way we declare the method is not a proper way. Reason is there is a performance drawback in there. As I have mentioned that method is a new function object. So each time when we create a new object, this function object will be created.
And also it will give inheritance issues, if we define our methods in the constructor.
Instead of that, we can define methods in prototype. Any function that you define in the prototype will be shared across all the instances of that function.

No comments:

Post a Comment