A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

一、实现效果
1、call 改变 this 指向;自动执行函数;参数列表形式传入
// 定义上下文
let ctx = {
  name: `yayxs`
};
// 定义函数
const fn = function(age, sex) {
  console.log(`${this.name}-${age}-${sex}`);
};

// 调用函数
fn(18, `男`);

2、apply 改变 this 指向;自动执行函数;参数数组形式传入
const fnCall = function(age, sex) {
  console.log(`call-${this.name}-${age}-${sex}`);
};

// fnCall(18, `男`); // call-undefined-18-男

fnCall.call(ctx, 18, `男`); // call-yayxs-18-男

// 总结:改变this指向,执行函数,参数列表传入

3、bind 返回一个改变了的 this 指向的函数;参数列表形式传入
const fnBind = function(age, sex) {
  console.log(`bind-${this.name}-${age}-${sex}`);
};

fnBind.bind(ctx); // 没有输出

const res = fnBind.bind(ctx);

console.log(res); // [Function: bound fnBind]

res(18, "男"); // bind-yayxs-18-男

二、自己实现
倘若自己手写代码实现call 与 apply
获取被绑定的函数
被绑定的函数追加到劫持替换的对象
被绑定的函数追加到劫持替换的对象
1、手写 call
Function.prototype.myCall = function(ctx, ...params) {
  // console.log(ctx); { name: 'yayxs' }
  // console.log(...params); 18 男
  if (typeof ctx === "object") {
    ctx = ctx || window;
  } else {
    ctx = null;
  }

  // 临时方法名
  let funcName = Symbol();

  // console.log(funcName);
  ctx[funcName] = this;
  // console.log(this); [Function: testFn]

  ctx[funcName](...params);
  delete ctx[funcName];
};

三、最后总结
总体来说,call apply bind 三个函数的作用都是用来改变this的指向。目前的 js 还存在回调函数这一现象,尤其在框架中一些异步回调也是十分的常见,难免this会迷失方向。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马