Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
90
rated 0 times [  91] [ 1]  / answers: 1 / hits: 20162  / 12 Years ago, wed, january 9, 2013, 12:00:00

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?


More From » javascript

 Answers
5

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.


[#80997] Monday, January 7, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kourtney

Total Points: 368
Total Questions: 103
Total Answers: 85

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
kourtney questions
Sun, Oct 4, 20, 00:00, 4 Years ago
Tue, Oct 29, 19, 00:00, 5 Years ago
Thu, Apr 4, 19, 00:00, 5 Years ago
Fri, Mar 1, 19, 00:00, 5 Years ago
;