Javascript:为函数原型添加方法 [英] Javascript: add methods to function prototype
本文介绍了Javascript:为函数原型添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更短的方式来写这个:
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
我正在使用require.js。我想知道我是否可以避免controller.prototype代码重复。
I'm using require.js. I wondered if I can avoid the controller.prototype code repetition.
推荐答案
使用助手功能
即使这比如果你必须这样做多个地方的答案可能有助于定义一个帮助方法:
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;
使用jQuery的扩展方法
我想我应该提一下 jQuery的扩展方法,因为它是在评论中提出来的,因为一般来说有更多功能比答案第一部分中定义的小助手方法:
Using jQuery's extend method
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:
var controller = function(){ /* ctor */};
return $.extend(controller.prototype,{
function1 : function(){
//Prototype method1
},
function2: function(){
//Prototype method2
},
function3 : function(){
//Prototype method3
}
});
其他图书馆
其他图书馆也有内置的类似功能,例如下划线的扩展方法或 Lo-Dash的分配方法
这篇关于Javascript:为函数原型添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文