Tra*_*ace 14 javascript methods prototype
是否有更短的方式来写这个:
var controller = function(){
/*--- constructor ---*/
};
controller.prototype.function1 = function(){
//Prototype method1
}
controller.prototype.function2 = function(){
//Prototype method2
}
controller.prototype.function3 = function(){
//Prototype method3
}
return controller
Run Code Online (Sandbox Code Playgroud)
我正在使用require.js.我想知道我是否可以避免controller.prototype代码重复.
kon*_*ked 14
即使这比你给出的答案要长,如果必须这样做,多个位置可能有助于定义一个辅助方法:
function protomix(constructor, mix){
for(var i in mix)
if(mix.hasOwnProperty(i))
constructor.prototype[i]=mix[i];
}
var controller = function(){
//constructor
};
protomix(controller, {
function1 : function(){
//Prototype method1
},
function2: function(){
//Prototype method2
},
function3 : function(){
//Prototype method3
}
});
return controller;
Run Code Online (Sandbox Code Playgroud)
我认为我应该提到 jQuery的extend方法,因为它是在注释中提出的,因为通常比答案的第一部分中定义的小帮助方法具有更多的功能:
var controller = function(){ /* ctor */};
return $.extend(controller.prototype,{
function1 : function(){
//Prototype method1
},
function2: function(){
//Prototype method2
},
function3 : function(){
//Prototype method3
}
});
Run Code Online (Sandbox Code Playgroud)
其他库也内置了类似的功能,例如下划线的extend方法或Lo-Dash的assign方法