在javascript中使用一组函数作为原型

using a group of functions as a prototypes in javascript

本文关键字:一组 函数 原型 javascript      更新时间:2023-09-26

使用like

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

我要做的是有几个函数,并能够将它们添加到Number, String,…或者其他的,我正在尝试找到一种方法有一组函数我可以给一个对象添加一个原型让它访问所有这些函数

您可以这样做。

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

根据https://stackoverflow.com/questions/16863073/dynamically-add-properties-to-the-prototype-object和一些小的变化,以适应我的问题,这是它:

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