https://zhuanlan.zhihu.com/p/85438296
Function.prototype.bind2 = function(context) {
if (typeof this !== "function") {
throw new Error(
"Function.prototype.bind - what is trying to be bound is not callable"
);
}
var self = this;
var args = Array.prototype.slice.call(arguments, 1)
var fNOP = function () {};
var fBound = function () {
var bindArgs = Array.prototype.slice.call(arguments);
// 當(dāng)作為構(gòu)造函數(shù)時(shí),this 指向?qū)嵗藭r(shí)結(jié)果為 true,將綁定函數(shù)的 this 指向該實(shí)例,可以讓實(shí)例獲得來自綁定函數(shù)的值
// 以上面的是 demo 為例,如果改成 `this instanceof fBound ? null : context`,實(shí)例只是一個(gè)空對象,將 null 改成 this ,實(shí)例會(huì)具有 habit 屬性
// 當(dāng)作為普通函數(shù)時(shí),this 指向 window,此時(shí)結(jié)果為 false,將綁定函數(shù)的 this 指向 context
return self.apply(
this instanceof fBound ? this : context,
args.concat(bindArgs)
);
};
// 修改返回函數(shù)的 prototype 為綁定函數(shù)的 prototype,實(shí)例就可以繼承綁定函數(shù)的原型中的值
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
}