手写bind
- 在写代码前,一定要分析这个api或者关键字实现了什么,拥有什么功能,如果对其原理认识不到时,也不能达到一比一还原
bind
- bind执行返回的是一个新的函数
- 这个函数可以被new关键字执行,执行后this指向window(原本的执行是)
- 返回的函数拥有其构造函数原型上的方法
下面我们看代码:
Function.prototype.mybind = function () {
if (typeof this !== 'function') {
throw new Error('The Caller is not a Function')
}
const argsArr = [...arguments]
const args = argsArr.shift();
const self = this;
const fToBind = function () {
console.log('返回函数的参数', arguments);
const isNew = this instanceof fToBind;
const context = isNew ? this : Object(args);
return self.apply(context, argsArr.concat([...arguments]));
}
if (self.prototype) {
fToBind.prototype = Object.create(self.prototype)
}
return fToBind
}
- 这样就实现了手写一个bind,其实很简单,在手写代码时我们首先要想清楚这个关键字或者api实现了什么,我们分布还原就好了