2020-01-04 第一章 灵活的语言-----JavaScript

1.试着定义一个即可为函数原型添加方法又可为其自身添加方法的addMethod方法。

Function.prototype.addMethod=function(name,fn){
this[name]=fn;
return this;
};
var method=function(){};
method.addMethod('checkname',function(){
//验证名称
console.log('名称');
return this;
}).addMethod('checktel',function(){
//验证电话号码
console.log('电话');
return this;
});
method.checkhand=function(){
//检查手
console.log('检查手手');
return this;
};
//调用
method.checkname().checktel().checkhand();

//执行结果


图片.png

类式调用:

Function.prototype.addMethod=function(name,fn){
this.prototype[name]=fn;
return this;
};
var Method=function(){};
 Method.addMethod('checkname',function(){
//验证名称
console.log('名称');
return this;
}).addMethod('checktel',function(){
//验证电话号码
console.log('电话');
return this;
});
Method.prototype.checkhand=function(){
//检查手
console.log('检查手手');
return this;
};
//调用
var m=new Method();
m.checkname().checktel().checkhand();

//执行结果


图片.png

使用类式调用时犯了一个错误

Function.prototype.addMethod=function(name,fn){
this.prototype[name]=fn;
return this;
};
var Method=function(){};
 Method.addMethod('checkname',function(){
//验证名称
console.log('名称');
return this;
}).addMethod('checktel',function(){
//验证电话号码
console.log('电话');
return this;
});
Method.prototype.checkhand=function(){
//检查手
console.log('检查手手');
return this;
};
Method.checkhand2=function(){
//检查手
console.log('检查手手2');
return this;
};
//调用
var m=new Method();
m.checkname().checktel().checkhand();
Method.checkhand2();
m.checkhand2();//报错,因为checkhand2不是原型的函数,所以没有被m继承
图片.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 接下来的几天里,我开始习惯按部就班的小学生活。当然,除了我最怕的写字。好多同学在幼儿园已经学过字写,一点也不费劲。...
    美西xyy阅读 347评论 0 3
  • 如果真心的付出 换来谎言的欺骗 心情真的很糟 情愿没遇见 不想听辩解 不想面对 只想独自一人 咀嚼 那怕巧舌如簧 ...
    花雨凤飞H阅读 196评论 8 4
  • 一棵树种下, 一棵棵树种下, 一片雪花落下, 片片雪花落下, 树木装扮了大地, 白雪铺就了童话, 蓝天和白雪拥抱,...
    泯炻阅读 125评论 0 0
  • 今天5点55起床,看完了《既清又浊的总督生涯》。接下来就写下《“不要钱”的大帅》和《既清又浊的总督生涯》看完后的感...
    晓寒云轻阅读 83评论 0 0
  • 第二次读村上春树《当我跑步时我谈些什么》。这次是用坐地铁的零碎时间,断断续续一个礼拜读完的。摘下的都为喜欢的句子。...
    AaronNotes阅读 744评论 0 51