- bind返回一个函数
- 闭包保存this, 执行的时候用apply或call绑定this
- js中new的优先级高于bind
Function.prototype._bind = function (context) {
if (typeof this !== "function") throw "type error"
const fn = this
return function O() {
// console.log(this instanceof O ? this : context);
return fn.apply(this instanceof O ? this : context, [...arguments])
}
}
function f() {
return 1
}
console.log(f._bind({ a: 1 })()); // 1
console.log(new (f._bind({ a: 1 }))()); // O{}