为什么使用{}代替新的Object()并使用[]而不是new Array()和true / false而不是new Boolean()? [英] Why use {} instead of new Object() and use [] instead of new Array() and true/false instead of new Boolean()?

查看:276
本文介绍了为什么使用{}代替新的Object()并使用[]而不是new Array()和true / false而不是new Boolean()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多人说你应该避免使用新的Object,新的Array()而是使用{}。 []和true / false。

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

使用文字结构获取对象或数组的新实例而不是使用new有什么好处?我知道Crockford不喜欢新的但是主要的论点是什么?

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?

推荐答案

对象和数组文字的优点而不是使用各自的构造函数是:

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)

在阵列的情况下,还有一个额外的优点:文字:单独使用 Array 构造函数创建一个包含单个成员的数组是不可能的。例如, [3] 将创建一个数组,其中一个元素是数字3,而 new Array(3)创建一个长度为3的数组。

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.

更新:现在问题已被编辑,以下段落不再相关。

关于布尔值,你似乎有一个误解: new Boolean(false)不一样假 Boolean()构造函数创建一个Boolean对象,而 false true 是布尔基元。事实上, new Boolean(false)在强制转换为布尔值时计算为 true ,例如 if 声明。简而言之,很少有理由使用 Boolean()构造函数。请改用 true false 。类似地,其他原语(如字符串和数字)具有相应的 String() Number()生成<$ c的构造函数$ c> String 和 Number 与原始字符串和数字不同的对象,通常应该避免使用。

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.

这篇关于为什么使用{}代替新的Object()并使用[]而不是new Array()和true / false而不是new Boolean()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆