登录
首页 >  文章 >  前端

手写callapplybind,JS面试必考技巧

时间:2026-03-27 19:03:42 370浏览 收藏

本文深入解析了JavaScript中改变函数this指向的三大核心方法——call、apply和bind,并手写实现了它们的简化版,涵盖参数传递差异(call传散列参数、apply传数组、bind返回预绑定函数)、Symbol防属性冲突、柯里化支持以及new调用时的优先级处理等关键细节;掌握这些实现不仅能扎实理解this机制的本质,更能在JS面试中展现对底层原理的深刻把握,是前端开发者进阶必备的硬核知识点。

手写call、apply、bind函数实现_js面试必备

在JavaScript中,callapplybind 是改变函数执行上下文的核心方法。面试中常被要求手写实现这三个方法,理解它们的原理对掌握this指向机制非常重要。下面分别实现它们的简化版,适用于大多数基础场景。

1. 手写 call 函数

call 的作用是调用函数,并指定其 this 指向,同时可以传入参数列表。

核心思路:将函数作为传入对象的一个临时方法调用,执行后删除该方法。

Function.prototype.myCall = function(context, ...args) {
  // 如果 context 为 null 或 undefined,则默认绑定到 window
  context = context || window;
  // 将函数挂到 context 上作为临时方法
  const fnSymbol = Symbol('fn');
  context[fnSymbol] = this; // this 指向调用 myCall 的函数
  // 执行函数并传参
  const result = context[fnSymbol](...args);
  // 删除临时属性
  delete context[fnSymbol];
  return result;
};

2. 手写 apply 函数

apply 和 call 类似,区别在于第二个参数是数组形式传参。

Function.prototype.myApply = function(context, args) {
  context = context || window;
  const fnSymbol = Symbol('fn');
  context[fnSymbol] = this;
  let result;
  if (args) {
    result = context[fnSymbol](...args); // 展开数组参数
  } else {
    result = context[fnSymbol]();
  }
  delete context[fnSymbol];
  return result;
};

3. 手写 bind 函数

bind 不立即执行函数,而是返回一个新函数,这个新函数的 this 被永久绑定到指定对象,支持预设部分参数(柯里化)。

注意:bind 返回的函数还能被 new 调用,此时 this 应指向实例,而不是绑定的对象。

Function.prototype.myBind = function(context, ...args1) {
  const fn = this; // 保存原函数
  const boundFn = function(...args2) {
    // 判断是否被 new 调用
    return fn.apply(
      this instanceof boundFn ? this : context, // new 时 this 指向实例
      args1.concat(args2) // 合并预设参数和调用时参数
    );
  };
  // 继承原函数原型
  boundFn.prototype = Object.create(this.prototype);
  return boundFn;
};

基本上就这些。掌握这三个手写实现,关键在于理解 this 的动态绑定机制、参数处理以及 new 调用的优先级高于 bind。面试时能清晰解释每一步的作用,加分不少。不复杂但容易忽略细节,比如 Symbol 防止属性覆盖、new 的特殊情况处理等。

好了,本文到此结束,带大家了解了《手写callapplybind,JS面试必考技巧》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>