改造业务代码

新手程序员,很容易犯写出面向过程的,留下很多全局变量的代码的错误。现在是时候简单的改进一下了。

    //函数原型添加一个addMethod方法,现在所有的函数都有addMethod方法了。
    Function.prototype.addMethod = function(name,fn){
        this[name] = fn;
        //在下面的的代码中,this指向methods函数。所以可以链式调用
        return this;
    };
    
    //等同于 var methods = new Function(){};
    var methods = function(){
    };
    methods
        .addMethod('checkName',function(){            console.log('检查了名字');
            return this;
        })
        .addMethod('checkPhone',function(){
            console.log('检查了手机');
            return this;
        });

    methods.checkName().checkPhone();
    //全局变量只有一个methods。这样就避免了全局变量污染。同时还有jQuery一样的链式调用。

 上面是函数式调用。还可以以类式的调用方式写。

    Function.prototype.addMethod = function(name,fn){
        this.prototype[name] = fn;
        return this;
    };

    var Methods = function(){};
    Methods
        .addMethod('checkName',function(){
            console.log('检查了名字');
            return this;
        })
        .addMethod('checkPhone',function(){
            console.log('检查了手机');
            return this;
        });

    var method=new Methods();
    method.checkName().checkPhone();
原文地址:https://www.cnblogs.com/liaozhenting/p/6880428.html