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

方法链式调用 #165

Open
louzhedong opened this issue Jul 12, 2019 · 0 comments
Open

方法链式调用 #165

louzhedong opened this issue Jul 12, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

设想,如果我们需要在每个函数执行时添加一个监控,来监控每个函数的执行情况,并且分为函数调用前以及函数调用后

在JavaScript中,万物皆对象。对于函数Function来说,如果我们在它的prototype中挂载一个属性,我们就可以在任何函数中访问到这个属性

基于以上,我们来实现一个方法的修饰器

实现

const FunProp = Function.prototype;

FunProp.before = function (beforeFn) {
  const _self = this;

  return function () {
    // 先执行before函数,再执行原函数
    beforeFn.apply(this, arguments);
    return _self.apply(this, arguments);
  }
}

FunProp.after = function (afterFn) {
  const _self = this;
  return function () {
    // 先执行原函数,再执行after函数
    const ret = _self.apply(this, arguments);
    afterFn.apply(this, arguments);
    return ret;
  }
}

使用方式

function test() {
	console.log("test");
}

const _test = test
	.before(function(){console.log("before")})
	.after(function(){console.log("after")});
	
_test();
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