Javascript:向函数原型添加方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23020290/
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: add methods to function prototype
提问by Trace
Is there a shorter way to write this:
有没有更短的方法来写这个:
var controller = function(){
/*--- constructor ---*/
};
controller.prototype.function1 = function(){
//Prototype method1
}
controller.prototype.function2 = function(){
//Prototype method2
}
controller.prototype.function3 = function(){
//Prototype method3
}
return controller
I'm using require.js. I wondered if I can avoid the controller.prototype code repetition.
我正在使用 require.js。我想知道是否可以避免 controller.prototype 代码重复。
采纳答案by konkked
With a Helper Function
带辅助功能
Even though this is longer than the answer given if you have to do this multiple places might be helpful to define a helper method:
即使这比给出的答案要长,如果您必须在多个地方执行此操作,也可能有助于定义辅助方法:
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;
Using jQuery's extend method
使用 jQuery 的扩展方法
I thought I should mention jQuery's extend method because it was brought up in a comment and because in general has more functionality than the small helper method defined in the first part of the answer:
我想我应该提到 jQuery 的扩展方法,因为它是在评论中提出的,而且通常比答案第一部分中定义的小助手方法具有更多的功能:
var controller = function(){ /* ctor */};
return $.extend(controller.prototype,{
function1 : function(){
//Prototype method1
},
function2: function(){
//Prototype method2
},
function3 : function(){
//Prototype method3
}
});
Other Libraries
其他图书馆
Other libraries also have similar functionality built in, such as underscore's extend methodor Lo-Dash's assign method
其他库也内置了类似的功能,比如underscore的extend方法或者Lo-Dash的assign方法
回答by user734320
Object.assign(controller.prototype, { function1: ... })
Object.assign(controller.prototype, { function1: ... })