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

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

问题描述

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

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.

某人可以做的不寻常的事将是阴影或分配到默认对象全局:

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对象将失败,但 {} 将起作用。

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()`和object literal notation有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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