设计模式:修饰器模式

定义:在不改动原有代码的情况下对已有的功能进行拓展,这种模式不会更改原有代码,对其他业务产生影响。

    //应用场景  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' })

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值