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

作者:纸飞机时间:2026-10-24 23:23:10浏览:101

本文详细解析如何利用 JavaScript 原型链手动实现 call、apply 和 bind 三个核心方法。通过修改函数上下文(this)并处理参数传递,深入理解这三个方法在改变函数执行环境及参数传递机制上的差异与联系,涵盖从基础逻辑到边界条件处理的完整实现思路。

首先,需要验证当前调用该方法的对象是否确实为函数类型。

若未显式指定 this 指向,则默认将其赋值为全局对象 window。

接着,将当前被调用的函数临时挂载到 context 对象上,通常命名为 fn。

然后,提取传入的参数列表,排除第一个 context 参数。

随后,使用提取的参数调用挂载在 context 上的 fn 函数。

调用结束后,必须从 context 对象中删除临时挂载的 fn 属性,以清理副作用。

最后,返回函数执行的结果。

  //普通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');

总结

以上就是本文的全部内容,希望能对大家有所帮助,也欢迎大家关注本站获取更多技术分享!

作者最新文章