【发布时间】:2011-04-08 17:32:37
【问题描述】:
我很好奇 new 关键字在后台除了更改 this 范围所指的内容之外还有什么作用。
例如,如果我们比较使用new 关键字让函数在对象上设置属性和方法与仅让函数返回一个新对象,那么新对象有什么额外的功能吗?
如果我不希望从函数构造函数创建多个对象,这是首选
var foo2 = function () {
var temp = "test";
return {
getLol: function () {
return temp;
},
setLol: function(value) {
temp = value;
}
};
}();
var foo = new function () {
var temp = "test";
this.getLol = function () {
return temp;
}
this.setLol = function(value) {
temp = value;
}
}();
萤火虫探查器告诉我使用 new 关键字稍快(2ms 而不是 3ms),在大型对象上 new 仍然明显更快?
[编辑]
另一个问题是关于真正大的对象构造函数是在函数底部有一个返回(它将有大量的本地函数)或者在函数的顶部有一些 this.bar = ...可读?什么是好的约定?
var MAIN = newfunction() {
this.bar = ...
// Lots of code
}();
var MAIN2 = function() {
// Lots of code
return {
bar: ...
}
}();
【问题讨论】:
标签: javascript oop prototype object new-operator