函数的祖先

ES5实现

  //es5
    Function.prototype.addMethod=function (name,fn) {
        //至于这里为什么不能用this[name]=fn;
        // 经过测试得知:
        //2, addMethod属于函数的静态方法,
        //3, addMethod中的this指向Methods,
        //4, Methods的原型是Object,
        //5, 不能将函数添加到this(即Methods)上, 否则是Methods的静态方法, 实例不能调用.
        this.prototype[name]=fn;
        //这里的this也是Methods, 这里返回this主要是为了链式调用addMethod.
        return this;
    }
    var Methods=function () {
        test1:"test1";
    };
    console.log(Methods);
    Methods.addMethod("checkName",function () {
        console.log("checkName");
       //这里的this是指Methods;这里的this,主要是为了链式调用checkEmail, checkPass, checkPass;
        return this;
    }).addMethod("checkEmail",function () {
        console.log("checkEmail");
        return this;
    }).addMethod("checkPass",function () {
        console.log("checkPass");
        return this;
    });
//    console.log(Methods["checkName"]);
//    console.log(Methods["checkEmail"]);
//    console.log(Methods["checkPass"]);
    var methods=new Methods();
    methods.checkName().checkEmail().checkPass();
    console.log("------------");

ES6

class Methods2 extends Function{
checkName(){
console.log(“checkName”);
return this;
}
checkEmail(){
console.log(“checkEmail”);
return this;
}
checkPass(){
console.log(“checkPass”);
}
}
let methods2=new Methods2();
methods2.checkName().checkEmail().checkPass();

—以上为阅读张荣铭前辈的JavaScript设计模式总结。
—github: https://github.com/hyuanyuanlisiwei/DesignPattern2

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值