zoukankan      html  css  js  c++  java
  • 改造业务代码

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

        //函数原型添加一个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();
  • 相关阅读:
    怎么用js实现jq的removeClass方法
    减少事件绑定次数
    JS setAttribute兼容
    css3常用动画+动画库
    小tip: transition与visibility
    image的srcset属性
    jqeury点击空白关闭弹窗
    卡片翻转效果
    div+css 圆角加阴影
    函数
  • 原文地址:https://www.cnblogs.com/liaozhenting/p/6880428.html
Copyright © 2011-2022 走看看