答案:call、apply和bind用于改变函数this指向,call与apply立即执行并分别接收参数列表和数组,bind返回绑定后的新函数且支持柯里化与new优先级处理。

在JavaScript中,call、apply 和 bind 是改变函数执行上下文的核心方法。面试中常被要求手写实现这三个方法,理解它们的原理对掌握this指向机制非常重要。下面分别实现它们的简化版,适用于大多数基础场景。
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;
};
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;
};
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 的特殊情况处理等。
以上就是手写call、apply、bind函数实现_js面试必备的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号