Javascript对象构造函数与对象文字 [英] Javascript object constructor vs object literal
问题描述
我正在通过我的第一个Javascript教程。
I'm going through my very first Javascript tutorial.
我刚刚发现了两种创建JS对象的方法。
I just found two ways to create a JS object.
var person = new Object();
person.name = "Tom";
person.age = "17";
和
var person = {};
person.name = "Tom";
person.name = "17"
这两种对象创建方式有何不同?由于第二个看起来更简单,我们是否可以在任何条件下使用它?
Any difference between these two ways of object creation? Since the second looks simpler, can we always use it under any condition?
推荐答案
第二种语法不仅更易于阅读,而且不仅可以在任何条件下工作,而且第一种语法可能不会在所有条件下工作:
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.
这篇关于Javascript对象构造函数与对象文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!