4

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?

0

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

4 Comments

Unless someone has redefined Object somewhere in the code ;)
@Jakob: I suppose you're right, but I doubt anyone would do that.
@jakob: i am reinitializing same object many times uisng new Obejct.Is it fine to replace that too with {} .Meaning same object refrace i want to point to new object
Yes, that is fine. My comment was mostly a joke, but also a hint that using Object is a bad idea, since it follows the normal scope resolution rules of the language. The only thing that could cause trouble for you would be if someone has been stupid enough to write something like: Object = function() { alert('Haha, Object is not what you think it is!'); }
-1

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 :)

2 Comments

This is does not really seem to answer the question at hand.
well i though it was helping but i forgot to mention things about both ways. thanx Felix

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.