手动实现call、apply、bind方法

简单介绍apply、call、bind方法

apply、call、bind方法的作用是改变函数中this的指向

  • apply/call:会自动调用,第一个参数都是设置this的指向,apply第二个参数为数组,call后面传入为参数列表。
  • bind:不会自动调用,会返回一个已经绑定好this的函数,传参与call一样

call()方法

/**
 * 涉及js的知识点:
 *  - 原型链:函数的原型链上添加方法
 *  - 剩余参数接收实参
 *  - 基本包装类型:非对象类型,通过Object包装
 *  - this的隐式绑定
 */

//如果没有传入第二个参数,"...args"默认为[]
Function.prototype.myCall = function (thisArg, ...args) {
  //1.拿到调用的函数
  let fn = this;

  //2.对传入的this包装为对象类型“Object(thisArg)”,this为undefined或null,则绑定为window
  thisArg = thisArg === null || thisArg === undefined ? window : Object(thisArg);

  //3.利用隐式绑定,调用函数
  thisArg.fn = fn;
  let result = thisArg.fn(...args); //拿到调用后的结果
  delete thisArg.fn; // 删除thisArg的fn属性

  //4.返回结果
  return result;
};

function sum(num1, num2) {
  console.log("sum", this);
  return num1 + num2;
}

// myCall中的this会被隐式绑定到foo
let result = sum.myCall(123, 1, 2);

console.log(result);

apply()方法

/**
 * 涉及js的知识点:
 *  - es6语法,给参数设置默认值
 *  - 原型链:函数的原型链上添加方法
 *  - 剩余参数接收实参
 *  - 基本包装类型:非对象类型,通过Object包装
 *  - this的隐式绑定
 */

//如果没有传入第二个参数,args默认为undefined,第十五行“...undefined”会报错,所以要设置默认值为[]
Function.prototype.myApply = function (thisArg, args = []) {
  //1.拿到调用的函数
  let fn = this;

  //2.对传入的this包装为对象类型“Object(thisArg)”,this为undefined或null,则绑定为window
  thisArg = thisArg === null || thisArg === undefined ? window : Object(thisArg);

  //3.利用隐式绑定,调用函数
  thisArg.fn = fn;
  let result = thisArg.fn(...args); //拿到调用后的结果
  delete thisArg.fn; //调用完后删除这个属性

  //5.返回结果
  return result;
};

function sum(num1, num2) {
  console.log("sum", this);
  return num1 + num2;
}

// myApply中的this会被隐式绑定到foo
let result = sum.myApply(123, [1, 2]);

console.log(result);

bind()方法

/**
 * 涉及js的知识点:
 *  - 原型链:函数的原型链上添加方法
 *  - 剩余参数接收实参
 *  - 基本包装类型:非对象类型,通过Object包装
 *  - this的隐式绑定
 *  - bind设计核心,需要一个代理函数
 */
Function.prototype.myBind = function (thisArg, ...args) {
  //1、拿到调用的函数
  let fn = this;

  //2、对传入的this包装为对象类型,this为undefined或null,则绑定为window
  thisArg = thisArg === undefined || thisArg === null ? window : Object(thisArg);

  function proxyFn(...laterArgs) {
    //3.1 利用隐式绑定给函数绑定this
    thisArg.fn = fn;
    //3.2 对前面传入的参数和后面传入的参数进行合并传入
    let result = thisArg.fn(...args, ...laterArgs);
    //3.3 删除thisArg的fn属性
    delete thisArg.fn;
    //3.4 返回执行后的结果
    return result;
  }

  //3、返回代理函数
  return proxyFn;
};

function sum(num1, num2, num3, num4) {
  console.log("sum", this);
  console.log(num1, num2, num3, num4);
  return num1 + num2;
}

let result = sum.myBind("123", 1);
console.log(result(2, 3, 4));

代码中注释有超详细解析,如有不足欢迎补充

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值