JavaScript中的新Object和新Object()之间有什么区别 [英] What is the difference between new Object and new Object() in JavaScript

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

问题描述


可能重复:

new MyObject(); vs new MyObject;

在一些文章中我看到以下语句创建新对象在JavaScript中:

In some articles I seen following statement to create new object in JavaScript:

var myObject = new Object;

以及某些网站:

var myObject = new Object();

两个陈述之间有什么区别,或者一个只是简写?

In there is any difference between two statements or one is just shorthand?

推荐答案

没有区别。当使用函数作为构造函数(即使用 new 运算符)且没有参数时,括号是可选的。当不使用 new 运算符时,在调用函数时总是需要括号。

There's no difference. Parentheses are optional when using a function as a constructor (i.e. with the new operator) and no parameters. When not using the new operator, parentheses are always required when calling a function.

如另一个答案中所述,通常最好使用对象文字。与使用 Object 构造函数相比,它具有以下优点:

As noted in another answer, it's generally preferable to use an object literal instead. It has the following advantages over using the Object constructor:


  • 允许简明的初始化属性(例如 var foo = {bar:cheese};

  • Shorter

  • 可能更快

  • 在被覆盖的 Object 函数的(不太可能的)事件中不受影响。

  • Allows concise initialization of properties (e.g. var foo = { bar: "cheese" };)
  • Shorter
  • Possibly faster
  • Unaffected in the (unlikely) event of the Object function being overwritten.

这篇关于JavaScript中的新Object和新Object()之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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