Function.prototype.myBind = function (context, ...bindArgs) {
/** self保存了当前函数
(即调用 myBind 的函数)的引用。
这样做是为了在稍后返回的函数中能够访问到原始函数。
)*/
const self = this;
/**
* 返回一个新的函数。当这个新函数被调用时,它将使用 apply 方法来调用原始函数,
* 同时将 this 上下文设置为 myBind 方法接收到的 context 参数。
*/
return function (...args) {
const newArgs = bindArgs.concat(args);
return self.apply(context, newArgs);
}
}
const person = { name: 'Alice' };
function greet(greeting, punctuation) {
return greeting + ' ' + this.name + punctuation;
}
// 使用myBind
const boundGreet = greet.myBind(person, 'Hello');
console.log(boundGreet('!')); // 输出: Hello, Alice!
手写bind
最新推荐文章于 2024-08-15 18:19:19 发布