最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

如何给javascript类型添加方法实例详解

来源:动视网 责编:小采 时间:2020-11-27 20:15:16
文档

如何给javascript类型添加方法实例详解

如何给javascript类型添加方法实例详解:给类型添加方法 javascript中允许给基本类型添加方法。如:boolean、string、Number 实例:在Function中添加一个method函数,该函数为Function添加其他自定义的函数(避免使用prototype),然后利用method函数想Function中添加一个add函数,
推荐度:
导读如何给javascript类型添加方法实例详解:给类型添加方法 javascript中允许给基本类型添加方法。如:boolean、string、Number 实例:在Function中添加一个method函数,该函数为Function添加其他自定义的函数(避免使用prototype),然后利用method函数想Function中添加一个add函数,

给类型添加方法
javascript中允许给基本类型添加方法。如:boolean、string、Number
实例:在Function中添加一个method函数,该函数为Function添加其他自定义的函数(避免使用prototype),然后利用method函数想Function中添加一个add函数,最后测试add函数在Function中确实存在。该方法将func函数添加到Function中,以name命名。然后,返回Function的对象

Function.prototype.method = function(name, func){
 // 避免覆盖已有的方法
 if(!this.prototype[name]){
 this.prototype[name] = func;
 }
 return this;
};
// 通过Function.method方法添加一个加法函数到Function,该函数的名称为“add”
Function.method("add", function(a, b){
 if(typeof a != 'number' || typeof b != 'number'){
 throw {
 'name' : "typeError",
 'message' : "add方法必须传入数字"
 };
 }
 return a + b;
});
// 调用Function的add方法是否存在
(function(){
 try{
 alert(Function.add(1, 3)); // 
输出:4 } catch(e){ if(e.name === 'typeError'){ alert(e.message); } } })(); // 去除字符串两端的空白 String.method("trim", function(){ return this.replace(/^\s+|\s+$/g, ''); }); alert('|' + " hello world ".trim() + '|'); // 输出: '|hello world|' // 添加数字的取整函数 Number.method("integer", function(){ // 可以通过此种方式调用函数,如:Math.random() == Math['random']() == Math["random"]() return Math[this < 0 ? 'ceil' : 'floor'](this); }); alert((-10 / 3).integer()); // 输出:-3

文档

如何给javascript类型添加方法实例详解

如何给javascript类型添加方法实例详解:给类型添加方法 javascript中允许给基本类型添加方法。如:boolean、string、Number 实例:在Function中添加一个method函数,该函数为Function添加其他自定义的函数(避免使用prototype),然后利用method函数想Function中添加一个add函数,
推荐度:
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top