Possible Duplicate:
creating objects - new object or object literal notation?
Literal notation VS. constructor to create objects in JavaScript
I'm going through my very first Javascript tutorial.
I just found two ways to create a JS object.
var person = new Object();
person.name = "Tom";
person.age = "17";
and
var person = {};
person.name = "Tom";
person.name = "17"
Any difference between these two ways of object creation? Since the second looks simpler, can we always use it under any condition?
Now the question is when should we be using Literal notation and constructor notation. The point is when we need only one instance with the same values then we can go with the literal notation else if we may need multiple instances, like the instance of a class, we can go for the constructor notation.
Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
The main difference here is what you can do with it. With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.
Object Literal. In plain English, an object literal is a comma-separated list of name-value pairs inside of curly braces. Those values can be properties and functions.
Not only is the second syntax easier to read and not only will it work under any condition, but the first syntax might not work under all conditions:
function Object() {
// Oh crap, we have redefined Object!
return []; // return an array because we are EVIL
}
var person = new Object(); // not what we think it is
But {}
, being a syntactic construct, is immune to such evil trickery.
In addition, the object literal notation can be partially optimized at parse time, since after all there's only one object type that could be created. That may result in a minuscule performance increase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With