Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - Why use {} instead of new Object() and use [] instead of new Array() and true/false instead of new Boolean()?

Many people say that you should avoid new Object, new Array()and instead use {}. [], and true/false.

What are the benefits of using the literal constructs to get a new instance of an Object or Array rather than using new? I konw that Crockford doesn't like new but is that the main argument?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The advantages of object and array literals over using the respective constructors are:

  • Shorter and more readable
  • Safer: literals will still work when the Array or Object constructors have been overridden
  • Possibly faster, though it's unlikely to be a major consideration (any bottlenecks will almost certainly originate elsewhere in code)

In the case of arrays, there's an additional advantage of a literal: it's impossible to create an array with a single member using the Array constructor alone. For example, [3] will create an array with one element which is the number 3, while new Array(3) creates an array of length 3.

Update: the following paragraph is no longer relevant now the question has been edited.

Regarding Booleans, you seem to have a misconception: new Boolean(false) is not the same as false. The Boolean() constructor creates a Boolean object whereas false and true are Boolean primitives. In fact, new Boolean(false) evaluates to true when coerced into a Boolean in, for example, an if statement. In short, there's very rarely a reason to use the Boolean() constructor. Use true and false instead. Similarly, other primitives such as strings and numbers have corresponding String() and Number() constructors that produce String and Number objects that are different to primitive strings and numbers and should generally be avoided.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...