JavaScript常用设计模式--装饰者模式

117 阅读1分钟

装饰者模式(Decorator Pattern)使用一种更为灵活的方式来动态给一个对象或者函数等添加额外信息

扩展功能和继承类似(extends)

扩展不同类的功能,和原始类并无关联

    class ZhangSan{
        constructor() {
            this.name = "张三";
        },
        release() {
            console.log("技能");
        }
    }
    
    let zhangsan = new ZhangSan();
    zhangsan.release(); // 技能
    
    function web() {
        console.log("web开发");
    }
    function java() {
        console.log("Java开发");
    }
    Function.prototype.Decorator = function(fn) {
        let _this = this;
        return function() {
            _this();
            fn();
        };
    }
    zhangsan.release.Decorator(web)();
    // 装饰者链
    zhangsan.release.Decorator(web).Decorator(java)();