jslearner
jslearner

Reputation: 22141

diffrerent ways to create object in javascript

What is the differnce between following two?

obj = new Object();

OR

obj = {};

In my code am asked to replace first notation with second one and the code is huge.Will replacing it cause any problem?

Upvotes: 4

Views: 3705

Answers (4)

Shadow Wizard
Shadow Wizard

Reputation: 66389

I will answer the second question:

Will replacing it cause any problem?

Nope, it won't cause any problem.

If you have for example those lines:

var obj = new Object("a");
//...code...
obj = new Object("b");
//...code...

Changing to this will have same result and no impacts:

var obj = { "a": 1 };
//...code...
obj = { "b": 2 };
//...code...

By assigning the variable with the = you're overwriting whatever it contained with the new value.

Upvotes: 2

yojimbo87
yojimbo87

Reputation: 68275

According to JavaScript Patterns book, using a built-in constructor (obj = new Object();) is an anti pattern for several reasons:

  • it's longer to type than literal (obj = {};)
  • literal is preferred because it emphasizes that objects are mutable hashes
  • scope resolution - possibility that you have created your own (local) constructor with the same name (interpreter needs to look up the scope chain)

Upvotes: 3

Marwan
Marwan

Reputation: 2402

Greetings Objects in JavaScript

1- var obj = { key1 : value1 , key2Asfunction : funciton1(){} };
obj.key1;
obj.key2Asfunction();

2- var obj = function()
{
this.obj1 = value1 ;
this.function1 = function(){};
}

var ob = new obj();
ob.obj1;
ob.function1();

if you need how to create the structure of the jquery frame work too i can help


Regrads :)

Upvotes: -1

icktoofay
icktoofay

Reputation: 128993

There is no difference. The former uses the Object constructor, whereas the latter is a literal, but there will be no difference in the resulting objects.

Upvotes: 0

Related Questions