Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object constructor vs object literal [duplicate]

Tags:

javascript

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?

like image 220
Terry Li Avatar asked Jan 09 '13 00:01

Terry Li


People also ask

When would you create an object using literal notation vs constructor notation?

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.

Whats the difference between an object and a object literal?

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.

What is the difference between creating an object using literal notation and creating an object using a constructor?

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.

What are objects literals JavaScript?

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.


1 Answers

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.

like image 107
Platinum Azure Avatar answered Oct 06 '22 01:10

Platinum Azure