How to create Objects in JavaScript?

How to create Objects in JavaScript?

An object can be created using various ways in JavaScript. First, we are going to look at object literal syntax.




A object can be defined in JavaScript as key value pairs. So, lets add some key value pairs inside the object literal syntax.




So, now we have our "car" object. We can access its members using dot notation.





To see the output, you should open developer tools or browser console.



But, if you want another car object you have to copy the whole code again. So, this method above is not a good way if you want to create multiple objects.

    So, lets look at creating objects using factory function. In this method, the object is returned when we call the function.



Creating objects is easier using this method.




You can access any member using dot notation.

Output


There is another way to create an object. That is using constructor function. It is the most preferred method. In this method we use “this” keyword to refer to the current object we are creating at the moment.



When creating objects, we should use “new” keyword.


So, those are the main ways of creating objects. When deciding which method to use, its based on problem you are going to solve and the personal preference.

Comments

Popular Posts

Getting started with GIT – Part 3

Getting started with GIT – Part 2

Getting started with GIT – Part 5