js bind 实现
实现 JavaScript 的 bind 方法
bind 方法用于创建一个新函数,该函数在调用时会将指定的 this 值绑定到函数,并可预设部分参数。以下是手动实现 bind 的核心逻辑:
核心实现代码
Function.prototype.myBind = function(context, ...args) {
const fn = this;
return function(...innerArgs) {
return fn.apply(context, [...args, ...innerArgs]);
};
};
实现说明
-
绑定
this和参数
通过闭包保存原始函数 (fn) 和目标上下文 (context),合并预设参数 (args) 和调用时传入的参数 (innerArgs)。 -
处理
new调用
完整实现需兼容构造函数调用(通过new操作符)。此时应忽略绑定的this,保留原型链:
Function.prototype.myBind = function(context, ...args) { const fn = this; const boundFn = function(...innerArgs) { return fn.apply( this instanceof boundFn ? this : context, [...args, ...innerArgs] ); }; boundFn.prototype = Object.create(fn.prototype); return boundFn; };
使用示例
const obj = { value: 42 };
function logValue(a, b) {
console.log(this.value + a + b);
}
const boundLog = logValue.myBind(obj, 10);
boundLog(20); // 输出: 72 (42 + 10 + 20)
关键点
- 通过
apply动态绑定this并传递参数。 - 闭包保存原始函数和预设参数。
- 构造函数调用时需检查
this instanceof boundFn。






