js bind 实现
实现 Function.prototype.bind 的 Polyfill
bind 方法创建一个新函数,当调用时,将其 this 关键字设置为提供的值,并在调用时传递给定的参数序列。
基本实现思路
bind 的核心功能包括:
- 绑定
this上下文。 - 支持预设参数(柯里化)。
- 返回的函数可以作为构造函数使用(通过
new调用时忽略绑定的this)。
完整代码实现
Function.prototype.myBind = function(context, ...args) {
const self = this;
const boundFunction = function(...innerArgs) {
// 判断是否通过 new 调用
const isNewCall = this instanceof boundFunction;
// 如果是 new 调用,使用新创建的 this,否则使用绑定的 context
return self.apply(
isNewCall ? this : context,
args.concat(innerArgs)
);
};
// 维护原型关系
if (this.prototype) {
boundFunction.prototype = Object.create(this.prototype);
}
return boundFunction;
};
关键点解析
绑定 this 上下文
通过闭包保存原始函数和绑定的 this 值,在调用时使用 apply 应用正确的上下文。
处理预设参数
使用剩余参数 ...args 收集绑定时传入的参数,在调用时与后续参数合并。
构造函数处理
通过检查 this instanceof boundFunction 判断是否通过 new 调用,确保构造函数能正确工作。
原型链维护
复制原函数的原型到绑定函数,确保通过 new 创建的对象能访问原型的属性和方法。
使用示例
const obj = { value: 42 };
function printValue(prefix, suffix) {
console.log(prefix + this.value + suffix);
}
const boundPrint = printValue.myBind(obj, "Value is ");
boundPrint("!"); // 输出: "Value is 42!"
// 作为构造函数
function Person(name) {
this.name = name;
}
const BoundPerson = Person.myBind(null);
const p = new BoundPerson("Alice");
console.log(p.name); // 输出: "Alice"
注意事项
原生 bind 方法返回的函数没有 prototype 属性,此实现为了支持构造函数场景保留了原型链。

当需要严格匹配原生行为时,可以省略原型处理部分,但会失去构造函数支持能力。






