在javascript中使用一组函数作为原型
using a group of functions as a prototypes in javascript
使用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");
相关文章:
- 简单的Javascript文本编辑器或一组函数
- 如何使用用户定义的相等函数在Javascript中创建一组用户定义的对象
- 如何在redux模块中创建一个helper类型的函数,从state返回一组经过过滤的只读数据
- 通过jquery.html()将一组数据传递给javascript函数
- 是否可以省略一组中间的 Javascript 函数参数
- 使用异步子例程对一组函数进行计时
- 首先触发一组函数,然后回调到最后一个函数
- 是否有一组限制可用于模拟JavaScript中的函数式编程
- 打字稿函数接受一个或一组对象
- jQuery中的函数来操作一组id
- 我如何创建一个函数来选择一组复选框的子集
- 如何在 Javascript 中使一组函数在另一组函数之后出现
- 如何使用 JavaScript 函数选择和修改一组 html
- Javascript函数,用于记住用户在其先前的访问权限中从一组下拉菜单选项中选择的内容
- javascript/nodejs:在大的、分块的数据集上同步调用一组类似的异步函数会导致内存泄漏
- 如何获得一组js函数在后台运行
- ReactJS组件PropTypes——用一组参数指定一个函数类型
- 使用传递给函数的参数动态地从一组数组中检索值
- 在javascript中使用一组函数作为原型
- 你能从一个字符串数组中创建一组函数吗