2020-01-04 第一章 灵活的语言-----JavaS
2020-01-04 本文已影响0人
_踮起脚尖看世界
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();
//执行结果
![](https://img.haomeiwen.com/i13909922/d56c435e4b71764b.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();
//执行结果
![](https://img.haomeiwen.com/i13909922/73e97b25d716b9d7.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继承
![](https://img.haomeiwen.com/i13909922/310e00b427fccfed.png)