louzhedong / blog

前端基础,深入以及算法数据结构

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

方法链式调用

louzhedong opened this issue · comments

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

在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();