`new Object()` 和对象文字符号有什么区别? [英] What is the difference between `new Object()` and object literal notation?

查看:22
本文介绍了`new Object()` 和对象文字符号有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个用于创建对象的基于构造函数的语法有什么区别:

What is the difference between this constructor-based syntax for creating an object:

person = new Object()

...还有这个文字语法:

...and this literal syntax:

person = {
    property1 : "Hello"
};

看起来两者都做同样的事情,尽管 JSLint 更喜欢你使用对象字面量表示法.

It appears that both do the same thing, although JSLint prefers you use object literal notation.

哪个更好,为什么?

推荐答案

他们都做同样的事情(除非有人做了一些不寻常的事情),除了你的第二个创建一个对象添加一个财产给它.但是文字符号在源代码中占用的空间更少.可以清楚地识别正在发生的事情,因此使用 new Object(),您实际上只是输入更多内容,并且(理论上,如果没有被 JavaScript 引擎优化)执行不必要的函数调用.

They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.

这些

person = new Object() /*You should put a semicolon here too.  
It's not required, but it is good practice.*/ 
-or-

person = {
    property1 : "Hello"
};

技术上不要做同样的事情.第一个只是创建一个对象.第二个创建一个并分配一个属性.为了让第一个相同,您需要第二个步骤来创建和分配属性.

technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.

某人可以做的不寻常的事情"是隐藏或分配给默认的 Object 全局:

The "something unusual" that someone could do would be to shadow or assign to the default Object global:

// Don't do this
Object = 23;

在那种非常不寻常的情况下,new Object 会失败,但 {} 会起作用.

In that highly-unusual case, new Object will fail but {} will work.

在实践中,永远没有理由使用 new Object 而不是 {}(除非你做过那件非常不寻常的事情).

In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).

这篇关于`new Object()` 和对象文字符号有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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