简体   繁体   中英

Why does JavaScript have different declarations for the same behavior?

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?

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.

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 .

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().

唯一可能要紧的事情是,如果您编写的程序会动态生成此类javascript……或者您是为某位大学老师的写作而写的,而该老师似乎有某种标准,但有时并不太有意义。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM