我正在阅读我的第一个 Javascript 教程。
我刚刚找到了两种创建 JS 对象的方法。
var person = new Object();
person.name = "Tom";
person.age = "17";
和
var person = {};
person.name = "Tom";
person.name = "17"
这两种对象创建方式有什么区别吗?既然第二个看起来更简单,我们可以在任何情况下都使用它吗?
我正在阅读我的第一个 Javascript 教程。
我刚刚找到了两种创建 JS 对象的方法。
var person = new Object();
person.name = "Tom";
person.age = "17";
和
var person = {};
person.name = "Tom";
person.name = "17"
这两种对象创建方式有什么区别吗?既然第二个看起来更简单,我们可以在任何情况下都使用它吗?
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.