Different Ways Of Creating Javascript Object: Part 1
Javascript is a flexible language and along with its flexibility comes it confusions. For example there are numerous ways of creating objects in JS. Which approach to use when and why , how objects differ created in one approach that the other, these finer details sometimes get overlooked in todays world of powerful frameworks. Nevertheless these details are important at conceptual level and you never know it could help debugging tricky issues
Most prevalent of creating an object is through "Object Literal" notation: Example: var testObj = {}
Nothing special here, it creates an empty Object.
Okay how about: var testObj = new Object();
//or
var testObj = Object();
Nothing different , all three of above does the same thing. However it is almost always preferred to use the literal notation because:
1.One can assign properties etc at the creation time
Example: var testObj = {name:"Abhijit"}
Here an object is created and a property named "name" is added at the creation time itself. To achieve same thing using constructor, it takes two steps
var testObj = new Object(); //and testObj.name = "Abhijit";
As you see
2. Literal notation is much shorter and easy to read
3. It performs slightly better than the constructor. To understand why see this amazing explanation in stackoverflow:javascript-vs-new-object-performance
4. If somebody wants to play a trick to you by overriding Object itself. Try this:
Object ="test";
var testObj = new Object() // or var testObj = Object();
You will get
TypeError: Object is not a function But literal var Object={} would still work just fine.
Crazy, huh!!
But new comes handy in other scenarios. I would cover that in part 2 of this series