Ray*_*nos 15 javascript oop prototype object new-operator
我很好奇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;
}
}();
Run Code Online (Sandbox Code Playgroud)
firebug探测器告诉我使用new关键字稍微快一点(2ms而不是3ms),对大型对象来说新的仍然明显更快?
[编辑]
另一个问题是真正大的对象构造函数在函数的底部有一个返回(它将具有大量的本地函数)或者有一些this.bar = ...在函数的顶部更具可读性?什么被认为是一个好的约定?
var MAIN = newfunction() {
this.bar = ...
// Lots of code
}();
var MAIN2 = function() {
// Lots of code
return {
bar: ...
}
}();
Run Code Online (Sandbox Code Playgroud)
Dan*_*llo 17
引用道格拉斯克罗克福德从好的部分书(第47页),回答这个问题的标题:
如果
new运算符是方法而不是运算符,则可以像这样实现:
Function.method('new', function () {
// Create a new object that inherits from the
// constructor's prototype.
var that = Object.create(this.prototype);
// Invoke the constructor, binding -this- to
// the new object.
var other = this.apply(that, arguments);
// If its return value isn't an object,
// substitute the new object.
return (typeof other === 'object' && other) || that;
});
Run Code Online (Sandbox Code Playgroud)
该Function.method方法实现如下.这为类(Source)添加了一个实例方法:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Run Code Online (Sandbox Code Playgroud)
进一步阅读: