当前位置:主页 > 网页前端 > JavaScript代码 >

Javascript动手实现call,bind,apply的代码详解

时间:2022-06-14 10:11:24 | 栏目:JavaScript代码 | 点击:

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');

总结

您可能感兴趣的文章:

相关文章