定义:在不改动原有代码的情况下对已有的功能进行拓展,这种模式不会更改原有代码,对其他业务产生影响。
//应用场景 axios的拦截器
//全局函数拦截(一般不推荐直接对Function直接操作,这里只是作为演示)
Function.prototype.before = function(beforeFn){
const _this = this
return function(){
//调用传入的前置函数
console.log('我是前置函数')
beforeFn.apply(this,arguments)
//执行原函数
_this.apply(this,arguments)
}
}
function test(){
console.log('我是主体函数')
}
test()
const test1 = test.before(function(){
console.log('前置函数主体')
})
test1()
function example(url,method,params){
console.log('示例函数主体')
console.log(url,method,params)
}
const beforeFn = example.before((url,method,params)=>{
params.token = 'Bearer asdasda2354656'
console.log('前置函数主体')
console.log(url,method,params)
console.log(this)
})
beforeFn('/api','GET',{ name:'猪猪侠' })
example('/api','GET',{ name:'xixixi' })