手撕函数

一 实现apply

   Function.prototype._apply = function (context) {
        if (typeof this !== 'function') {
            throw new TypeError('not funciton')
        }
        context.fn = this;  //this 指向调用_apply的函数
        let args = arguments[1];
        let result = context.fn(...args);
        delete context.fn;
        return result;
    }

二 实现call

Function.prototype._call = function(context,...args) {
      if (typeof this !== 'function') {
            throw new TypeError('not funciton')
      }
     context.fn = this;//同样this指向调用_call的函数。
     let result = context.fn(...args);
     delete context.fn;
     return reusult
  }
     

三 实现bind函数

Function.prototype._bind = function(context) {
    let fn = this;
    let args = [].slice.call(arguments,1);
    let F =function() {
        fn.apply(this instanceof F ?this:context,args.concat([...arguments]))
    }//如果通过new 绑定的函数,则把fn指向新对象,否则,指向传入的context
    F.prototype = fn.prototype;
   //如果new一个F对象,修改new后的对象指向新fn
   return F;
}

四 实现防抖函数

    function debounce(fn,wait) {
        let timer = null;
        return function() {
            clearTimeout(timer);
            let args = arguments;
            let context = this;
            timer = setTimeout(() => {
                fn.apply(context,args)
            }, wait) 
        }
           
    }

五 实现节流函数

function throttle(fn, wait) {
        let timer = null;
        return function () {
            let args = arguments;
            let context = this;
            if (!timer) {
               timer = setTimeout(() => {
                    fn.apply(this, args);
                    timer = null;
                }, wait)
            }


        }
    }
 function throttle2(fn,wait) {
        let prev = Date.now();
        return function() {
            let now = Date.now();
            let context = this;
            let args = arguments;
            if(now-prev>=wait) {
                fn.apply(context,args);
                prev = Date.now()
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值