bind 函数通过传入一个对象,返回一个 this 指向传入对象的新函数。这个函数的 this 指向除了使用 new 时会被改变,其他情况下都不会改变。
Function.prototype.myBind = function (ctx, ...args) {
// 判断调用对象是否为函数
if (typeof this !== 'function') {
throw new TypeError(`${this}.myBind is not a function`);
}
// 保存当前函数的引用
const fn = this;
return function Fn(...restArgs) {
if (this instanceof Fn) { // 或使用 new.target 判断是否通过 new 调用
return new fn(...args, ...restArgs);
}
return fn.apply(ctx, [...args, ...restArgs]);
};
};
测试:
function fn(a, b, c) {
console.log('fn called');
console.log(`arguments:`, a, b, c);
console.log('this:', this);
return 'result';
}
const newFn = fn.myBind('ctx', 1);
console.log(newFn(2, 3));
// 输出结果:
// fn called
// arguments: 1 2 3
// this: [String: 'ctx']
// result
console.log(new newFn(2, 3));
// 输出结果:
// fn called
// arguments: 1 2 3
// this: fn {}
// fn {}
663

被折叠的 条评论
为什么被折叠?



