1

简单优化 方法的调用(面向对象+设计者模式) 水一下

       //例子如下
function hongdeng (){
    console.log('红灯');
}
function huangdeng (){
    console.log('黄灯');
}
function lvdeng (){
    console.log('绿灯');
}
    //不方便调用,也不方便多人开发后的使用容易被覆盖,我们将他放到一个对象里面就非常轻松解决这个问题
    var honglvdeng = {
        hongdeng: function(){
            console.log('红灯');
        },
        huangdeng: function(){
            console.log('黄灯');
        },
        lvdeng: function (){
            console.log('绿灯');
        }
    }
    //发现在调用的时候依旧不方便需要多次书写对象,诞生了更优的方式
    var honglvdeng = {
        hongdeng: function(){
            console.log('红灯');
            return this;
        },
        huangdeng: function(){
            console.log('黄灯');
            return this;
        },
        lvdeng: function (){
            console.log('绿灯');
            return this;
        }
    }
    honglvdeng.hongdeng().huangdeng().lvdeng()
    //在简单优化一下
    var honglvdeng = {
        hongdeng: function(){
            console.log('红灯');
            return this;
        },
        huangdeng: function(){
            console.log('黄灯');
            return this;
        },
        lvdeng: function (){
            console.log('绿灯');
            return this;
        }
    }
    //在优化一下方便他人使用
    var honglvdeng = function(){};
    honglvdeng.prototype = {
        a : 1,
        hongdeng: function(){
            console.log('红灯');
            this.a ++;
            return this;
        },
        huangdeng: function(){
            console.log('黄灯');
            this.a ++;
            return this;
        },
        lvdeng: function (){
            console.log('绿灯');
            this.a ++;
            return this;
        }
    }
 var chenhonglvdeng = new honglvdeng();
 chenhonglvdeng.hongdeng().huangdeng().lvdeng();
 console.log(chenhonglvdeng.a);
 var chenhonglvdeng2 = new honglvdeng();
 chenhonglvdeng2.hongdeng().huangdeng();
 console.log(chenhonglvdeng2.a);
posted @ 2022-05-13 21:51  死胖子|土豆  阅读(29)  评论(0)    收藏  举报
/* 看板娘 */ canvas#live2dcanvas { border: 0 !important; left: 0; } /* 看板娘 */