Function.prototype.bind | 绑定函数
- 改变
this、预置参数、new的表现
语法
function.bind(thisArg[, arg1[, arg2[, ...]]])
参数
thisArg当绑定函数被调用时,该参数会作为原函数运行时的
this指向。当使用new操作符调用绑定函数时,该参数无效arg1, arg2, ...当绑定函数被调用时,这些参数将置于实参之前传递给被绑定的方法
实现
- 闭包的使用:保存私有变量
this和prefixArgs - 判断是否通过
new调用当前函数 - 使用
apply在执行时改变函数的this指向 - 指向原函数的
prototype - 返回函数
/**
* 函数的bind方法
* @param { object } context 上下文
* @param { any } prefixArgs 参数
* @returns { function } 返回函数
*
* */
Function.prototype.bind = function (context, ...prefixArgs) {
if (typeof this !== 'function') {
throw new TypeError('Bind must be called on a function');
}
let self = this;
let fBound = function (...args) {
// 判断是否用了 new, 考虑new的情况
if(this instanceof fBound) {
return new self(...prefixArgs, ...args)
}
return self.apply(context, [...prefixArgs, ...args]);
}
// 让 bind 返回的新函数的 prototype 指向原函数的 prototype
fBound.prototype = Object.create(self.prototype);
return fBound;
}