Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 设计模式(装饰者模式) #35

Open
wl05 opened this issue May 30, 2019 · 0 comments
Open

javascript 设计模式(装饰者模式) #35

wl05 opened this issue May 30, 2019 · 0 comments

Comments

@wl05
Copy link
Owner

wl05 commented May 30, 2019

概念

在不改变原对象的基础上,通过对其进行包装拓展(添加属性或者方法)使原有对象可以满足用户更复杂的需求。

实现

Function.prototype.before = function (beforefn) {
    var __self = this; // 保存原函数的引用
    return function () { // 返回包含了原函数和新函数的"代理"函数
        beforefn.apply(this, arguments); // 执行新函数,且保证 this 不被劫持,新函数接受的参数
        // 也会被原封不动地传入原函数,新函数在原函数之前执行
        return __self.apply(this, arguments); // 执行原函数并返回原函数的执行结果,
        // 并且保证 this 不被劫持
    }
}
Function.prototype.after = function (afterfn) {
    var __self = this;
    return function () {
        var ret = __self.apply(this, arguments);
        afterfn.apply(this, arguments);
        return ret;
    }
};


function a(params) {
    console.log(params)
}
function b(params) {
    params.b = '2'
    console.log(params)
}
var c = a.after(b)
c({ a: '1' })

参考资料

  1. JavaScript设计模式与开发实践-第15章-装饰者模式
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant