實(shí)現(xiàn)bind的步驟靠闭,我們可以分解成為三部分:
- 修改this指向
- 動態(tài)傳遞參數(shù)
- 兼容new關(guān)鍵字
Function.prototype.mBind = function (context) {
// 判斷調(diào)用對象是否為函數(shù)
if (typeof this !== "function") {
throw new TypeError("Error");
}
// 獲取參數(shù)
const args = [...arguments].slice(1),
self = this;
return function Fn() {
// 根據(jù)調(diào)用方式摘刑,傳入不同綁定值
oo = this instanceof Fn ? new self(...arguments) : context //
return self.apply(oo, args.concat(...arguments));
}
}
// 測試
function p(name, age) {
console.log('打印:', this.value, name, age);
}
var obj = {
value: '易'
}
p.mBind(obj, '四鴰崠')(16); //打印: 易 四鴰崠 16