js 手写bind
作者:互联网
- 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{}
标签:function,console,log,bind,js,._,return,手写 来源: https://www.cnblogs.com/ltfxy/p/16375862.html