js 动手实现一个call、bind 、apply

  1. ​​​​​​检查当前调用的是否为函数
  2. 如果当前没有传入指向的this,则赋值为window
  3. 将fn指向当前调用的函数
  4. 获取传入的参数
  5. 将参数传入fn进行调用
  6. 将对象上的fn删除
  7. 返回结果

  //普通call的实现
  function hello(){
      console.log('hello 我是'+this.name);
  };
  let person = {
      name:'krys'
  };
  var name = 'liang';//只有var的变量属于window
  hello();// 'hello 我是liang'
  hello.call(person);//'hello 我是krys'
  hello.call();//'hello 我是liang'
  let person2 = {
      name:'lwl'
  }
  Function.prototype.mycall = function(context){
      //不传入参数的时候,默认为window
      if(typeof this !== "function"){
          throw new TypeError('Error');
      }
      context = context || window;
      context.fn = this;//fn就是上面的hello方法
      const args = [...arguments].slice(1);//第一个参数不要
      const result = context.fn(...args);//把剩下的其他参数传给hello
      delete context.fn;
      return result;
  }
  hello.mycall(person2);
function getParams(){
        console.log('我是',this.name,'获取一些参数',...arguments);
    }
    let person3 = {
        name:'hhh'
    };
    getParams.apply(person3,['hello','world'])
    Function.prototype.myApply = function(context){
        if(typeof this !== "function"){
            throw new TypeError()
        }
        context = context || window;
        context.fn = this;
        let result;
        if(arguments[1]){
            //如果有传入参数数组
            console.log(arguments[1])
            result  = context.fn(...arguments[1]);
        }else{
            result  = context.fn();
        }
        delete context.fn;
        return result;


    }
    getParams.myApply({name:'llll'},['jjj','kkkk','llll']);
function getParams(){
        console.log('我是',this.name,'获取一些参数',...arguments);
    }
    let person3 = {
        name:'hhh'
    };
    let person4 = {
        name:'tttt'
    };
    getParams.bind(person3,'hello','world')
    getParams.bind(person4,'hello','world')('jjj','kkk');
    Function.prototype.myBind = function(context){
        if(typeof this !== "function"){
            throw new TypeError()
        }
        context = context || window;
        const _that = this;
        const args = [...arguments].slice(1);
        return function F(){
            if(this instanceof F){
                return new _that(...args,...arguments);//这里的arguments是上面的jjj kkk
            }
            return _that.apply(context,args.concat(...arguments));//这里的arguments是上面的jjj kkk
        }
       


    }
    getParams.myBind({name:'llll'},'jjj','kkkk','llll')('hhhhllll');

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值