js bound实现
实现 JavaScript 中的 bind 方法
bind 方法用于创建一个新函数,该函数在调用时会将 this 关键字绑定到指定的值,并可预先传入部分参数。以下是手动实现 bind 的几种方式:
基础实现
Function.prototype.myBind = function(context, ...args) {
const fn = this;
return function(...innerArgs) {
return fn.apply(context, [...args, ...innerArgs]);
};
};
context是绑定的this值。args是预先传入的参数。- 返回的函数会合并预先传入的参数和后续调用时传入的参数。
支持 new 操作符的实现
原生 bind 允许通过 new 调用绑定的函数,此时 this 绑定会失效。改进版本如下:
Function.prototype.myBind = function(context, ...args) {
const fn = this;
const boundFn = function(...innerArgs) {
// 判断是否通过 new 调用
const isNewCall = this instanceof boundFn;
return fn.apply(isNewCall ? this : context, [...args, ...innerArgs]);
};
// 继承原型链
boundFn.prototype = Object.create(fn.prototype);
return boundFn;
};
- 通过
this instanceof boundFn判断是否通过new调用。 - 如果是
new调用,则忽略绑定的context,使用新创建的this。
完整实现(兼容性)
以下是一个更完整的实现,兼容更多边界情况:

Function.prototype.myBind = function(context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Bind must be called on a function');
}
const fn = this;
const boundFn = function(...innerArgs) {
const isNewCall = this instanceof boundFn;
return fn.apply(isNewCall ? this : context, [...args, ...innerArgs]);
};
// 处理原型链
if (fn.prototype) {
boundFn.prototype = Object.create(fn.prototype);
}
return boundFn;
};
- 检查调用者是否为函数。
- 正确处理原型链,避免未定义
prototype的情况。
使用示例
const obj = { value: 42 };
function logValue(a, b) {
console.log(this.value, a, b);
}
const boundLog = logValue.myBind(obj, 10);
boundLog(20); // 输出: 42 10 20
const instance = new boundLog(20); // this 指向新创建的对象
注意事项
bind返回的函数没有prototype属性,但可以通过new调用。- 原生
bind的性能更高,手动实现仅用于理解原理。 - 如果绑定的函数是箭头函数,
this不会被重新绑定,因为箭头函数的this在定义时确定。






