bind方法实现思路:
1、bind方法不会立即执行,会返回一个函数(闭包)
2、实现作用域绑定(apply)
3、参数传递(apply的数组传参)
4、当绑定函数作为构造函数时,绑定的this会失效并进行原型继承
Function.prototype.mybind = function(context) {
if(typeof this !== 'function'){
throw new Error('Mybind should be called by function !');
return;
}
const self = this;
const args = [ ...arguments ].slice(1);
let inner = function() {
let _this = this instanceof inner ? this : context;
return self.apply(_this, [ ...args, ...arguments ]);
}
let Fn = function() {};
Fn.prototype = this.prototype;
inner.prototype = new Fn();
// inner.prototype = this.prototype;
// 如果写inner.prototype = this.prototype
// 那么当改变inner的原型时,目标函数的原型也会被改变
return inner;
}