JavaScript 中 bind 方法的特性
- this 指向:
bind
方法会创建一个新函数,这个新函数的 this
会被绑定到 bind
方法的第一个参数上。即使新函数在其他地方被调用,其 this
始终指向绑定的值。
- 参数传递:
bind
方法除了第一个参数用于绑定 this
外,后续传入的参数会作为新函数的预设参数,在新函数调用时,会将这些预设参数与新函数实际传入的参数按照顺序合并,作为新函数的最终参数。
手动模拟实现类似 bind 功能的函数
Function.prototype.myBind = function (context) {
if (typeof this!== 'function') {
throw new TypeError('this must be a function');
}
const self = this;
const args = Array.prototype.slice.call(arguments, 1);
return function () {
const innerArgs = Array.prototype.slice.call(arguments);
const finalArgs = args.concat(innerArgs);
return self.apply(context, finalArgs);
};
};