17

可能重复:
创建对象 - 新对象或对象文字表示法?
文字符号VS。在 JavaScript 中创建对象的构造函数

我正在阅读我的第一个 Javascript 教程。

我刚刚找到了两种创建 JS 对象的方法。

var person = new Object();
person.name = "Tom";
person.age = "17";

var person = {};
person.name = "Tom";
person.name = "17"

这两种对象创建方式有什么区别吗?既然第二个看起来更简单,我们可以在任何情况下都使用它吗?

4

1 回答 1

28

Not only is the second syntax easier to read and not only will it work under any condition, but the first syntax might not work under all conditions:

function Object() {
    // Oh crap, we have redefined Object!
    return [];    // return an array because we are EVIL
}

var person = new Object();   // not what we think it is

But {}, being a syntactic construct, is immune to such evil trickery.

In addition, the object literal notation can be partially optimized at parse time, since after all there's only one object type that could be created. That may result in a minuscule performance increase.

于 2013-01-09T00:14:39.967 回答