Javascript 对象构造函数与对象字面量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14226299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript object constructor vs object literal
提问by Terry Li
Possible Duplicate:
creating objects - new object or object literal notation?
Literal notation VS. constructor to create objects in JavaScript
I'm going through my very first Javascript tutorial.
我正在学习我的第一个 Javascript 教程。
I just found two ways to create a JS object.
我刚刚找到了两种创建 JS 对象的方法。
var person = new Object();
person.name = "Tom";
person.age = "17";
and
和
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?
这两种创建对象的方式有什么区别吗?既然第二个看起来更简单,那么我们可以在任何情况下都使用它吗?
回答by Platinum Azure
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.
此外,对象文字符号可以在解析时部分优化,因为毕竟只能创建一种对象类型。这可能会导致微不足道的性能提升。