1

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

4
  • Have you tried using Object.prototype? Commented Aug 9, 2016 at 13:26
  • then it applies for everything? Number, String, Array, ...? Commented Aug 9, 2016 at 13:28
  • Subclass String with ES2015 class syntax: class MyString extends String {/* your methods */}. Never mutate built-in prototypes. Commented Aug 9, 2016 at 13:29
  • basically it's not completely clear what you're trying to achieve Commented Aug 9, 2016 at 13:30

2 Answers 2

1

You can do something like this.

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

var str = "String"; 

console.log(str.myMethods().endsWith("ing"));
console.log(str.myMethods().endsWith("asdf"));
console.log(str.myMethods().beginsWith("Str")); 

Sign up to request clarification or add additional context in comments.

Comments

0

According to https://stackoverflow.com/questions/16863073/dynamically-add-properties-to-the-prototype-object and some minor changes to suit my problem, this is it:

    var methods = {
        foo: function (x) { alert('foo:' + x); },
        bar: function(x){ alert('bar:'+x);}
    }
  for(var m in methods) String.prototype[m] = methods[m];

    "test".foo("aaaa");
    "test".bar("aaaa");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.