// _bind.js
// 别人写法
Function.prototype._bind1 = function (context, ...args) {
if (!context || context === null) context = window;
const fn = Symbol();
context[fn] = this;
const _this = this;
const result = function (...innerArgs) {
if (this instanceof _this) {
this[fn] = _this;
this[fn](...[...args, ...innerArgs]);
delete this[fn];
} else {
context[fn](...[...args, ...innerArgs]);
delete context[fn];
}
};
result.prototype = Object.create(this.prototype);
return result;
};
// 官方写法
Function.prototype._bind2 = function () {
const _this = this;
const realThis = arguments[0] ? arguments[0] : window;
const restParams = arguments && arguments.slice(1);
if (typeof _this !== ‘function‘) {
throw new TypeError(‘Function.prototype.bind - ‘ + ‘what is trying to be bound is not callable‘);
}
return function () {
_this.call(realThis, ...restParams);
};
};
手写bind