Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 3 months ago 13
Javascript Question

using a group of functions as a prototypes in javascript

We use like

String.prototype.EndsWith = function(){ ... }


What I'm trying to do is to have several functions and be able to add them to Number, String, ... or anything else, I'm trying to find a way that has a group of functions and I can just add one prototype to an object letting it access all of these functions

Answer

You can do something like this.

String.prototype.myMethods = function(){
  var self = this; 
  return {
    endsWith: function(str){
      if (self.substr(str.length-1).localeCompare(str)){
        return true; 
      }
      return false; 
    }
  };
};

var str = "String"; 

console.log(str.myMethods().endsWith("ing"));

Comments