js bind 实现
实现 bind 方法的核心思路
bind 方法的主要功能是创建一个新函数,该函数在调用时会将指定的 this 值和预设的参数作为原始函数的执行上下文和参数。以下是实现的关键步骤:
绑定 this 和预设参数
通过闭包保存原始函数、绑定的 this 值(thisArg)和预设参数(presetArgs)。返回的新函数在调用时,将绑定的 this 值和预设参数与调用时传入的参数合并,传递给原始函数。
Function.prototype.myBind = function(thisArg, ...presetArgs) {
const originalFunc = this;
return function(...args) {
return originalFunc.apply(thisArg, [...presetArgs, ...args]);
};
};
处理 new 操作符的情况
当使用 new 调用绑定的函数时,应忽略绑定的 this 值,以新创建的对象作为 this。此时需要检查是否通过 new 调用(通过 instanceof 或 new.target)。
Function.prototype.myBind = function(thisArg, ...presetArgs) {
const originalFunc = this;
const boundFunc = function(...args) {
const isNewCall = this instanceof boundFunc;
return originalFunc.apply(
isNewCall ? this : thisArg,
[...presetArgs, ...args]
);
};
boundFunc.prototype = originalFunc.prototype;
return boundFunc;
};
完整代码示例
以下是一个完整的 bind 实现,支持 this 绑定、参数预设和 new 操作符:

Function.prototype.myBind = function(thisArg, ...presetArgs) {
const originalFunc = this;
if (typeof originalFunc !== 'function') {
throw new TypeError('Bind must be called on a function');
}
const boundFunc = function(...args) {
const isNewCall = new.target !== undefined || this instanceof boundFunc;
return originalFunc.apply(
isNewCall ? this : thisArg,
[...presetArgs, ...args]
);
};
boundFunc.prototype = originalFunc.prototype;
return boundFunc;
};
使用示例
const obj = { value: 42 };
function test(a, b) {
console.log(this.value, a, b);
}
const boundTest = test.myBind(obj, 'preset');
boundTest('dynamic'); // 输出: 42 preset dynamic
const instance = new boundTest('dynamic'); // 输出: undefined preset dynamic
注意事项
- 原生
bind返回的函数没有prototype属性,但上述实现为了支持new操作符,保留了prototype。 - 如果不需要支持
new操作符,可以简化实现。






