Reputation: 10971
Why should I declare
var foo = {}
instead of
var foo = new Object();
in JavaScript if they are similar? Does the same applies to
foo[0].bar = new Function(){ "return hello"};
as in in
foo[0].bar = function(){return "hello"};
? Is it an efficiency matter? Does it make difference?
Upvotes: 2
Views: 89
Reputation: 146201
Actually
var foo = {}
and
var foo = new Object();
does the same thing (both expressions create an empty Object
) but it's better to use shorter version (object literal
), it takes less space time to write and another thing that using object literal
you can create and assign values/properties to an Object
as follows
person = {
property1 : "Hello"
};
but using new Object()
you need to create it first and then assign values/properties as follows
person = new Object();
person.property1 = "Hello";
In your second example (function vs new function
) there is a difference because new Function
is slower
and you can take a look at this test here.
Upvotes: 2
Reputation: 26696
The new Function()
constructor doesn't really work that way.
It's called like:
var myFunc = new Function("param1", "param2", "message", "/*function-body-as-a-string*/ console.log(message); return param1 + \"=\" + param2;");
ie: really dumb, error-prone, stupid-slow (uses eval) and a security-hole. Don't use it.
Upvotes: 0
Reputation: 6055
I remember reading the following from w3fools.com:
personObj=new Object();
This is a bad and unnecessary use of the
new
keyword. They should be using and advocating the object literal syntax ({}
) for creating new objects.
It doesn't say why, only that we should.
Upvotes: 2
Reputation: 746
The only times it might matter is if your writing a program that generates such javascript dynamically ... or your writing for a certain teacher in college who seems to have a certain standard that doesn't quite make sense at times.
Upvotes: 0
Reputation: 1043
No there isn't any efficiency increase or decrease, its just shorthand like using ? : for if/else..
I always use shorthand {} but if you are going to have a beginner reading your code you may want to use new Object().
Upvotes: 0