[removed] add methods to function prototype

前端 未结 2 968
陌清茗
陌清茗 2021-02-13 12:17

Is there a shorter way to write this:

var controller = function(){ 
    /*--- constructor ---*/
}; 

controller.prototype.function1 = function(){ 
    //Prototy         


        
相关标签:
2条回答
  • 2021-02-13 12:34

    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

    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
       } 
    });
    

    Other Libraries

    Other libraries also have similar functionality built in, such as underscore's extend method or Lo-Dash's assign method

    0 讨论(0)
  • 2021-02-13 12:39

    Object.assign(controller.prototype, { function1: ... })

    0 讨论(0)
提交回复
热议问题