javascript中使用new已经是很普遍的事情,特别是在OOP编程中,包括继承、实例化等等。可是使用new的时候,开销甚大,就在于它背后要执行的一系列操作。但是,我们可以使用很多其他的方式来代替new的作用。比如使用对象字面量{},还有数组[]的方式来代替类的实例化,比如:new Function,new String,new Number,new Array等等内置的类。记住:不要使用上面例举的实例化方式。new Function我们可以使用函数字面量来代替:var foo=function(){},new Array可以使用数组字面量的方式:var arr=[]等等,字面量的开销比new要小很多。具体的例子如下:
Bad: frames[0].onfocus=new Function("document.bgColor='#f00'");
Better: frames[0].onfocus = function () {document.bgColor = 'antiquewhite';};
Bad:
myObj = new function () {
this.type = 'core';
};
Better:
myObj = {
type: 'core'
};
Bad:
var foo = new function() {
function processMessages(message) {
alert("Message: " + message.content);
}
this.init = function() {
subscribe("/mytopic", this, processMessages);
}
}
Better:
var foo = (function () {
function processMessages(message) {
alert("Message: " + message.content);
}
return {
init: function () {
subscribe("/mytopic", this, processMessages);
}
};
})();
在继承方面,我们都可以代替new来实例化,具体看《元编程的思想》,《函数化实现“伪继承机制”》
function createFunc(fn){
var f = fn;
var func = function(){
return f.apply(this, arguments);
}
for (var key in f.prototpe) { //复制
func.prototype[key] = f.prototype[key];
}
func.prototype.toString=function(){ return "function";} //扩展的属性
return func;
}
上面createFunc函数的作用就是就是在参数fn的基础上进行扩展,避免了使用new来实现继承,扩展子类。但是,不言而喻,使用new来进行继承和实例化在某些场合比其他任何替代方式都适合和简洁。在对实例化内置类的时候,使用字面量或者简单的数字、字符串比使用new高效多了。