Function.prototype.myBind=function(context){
if(typeof this!=='function'){
throw new TypeError('error')
}
let args=[...arguments].slice(1)
let fn=this
return function Fn(){
//this instanceof Fn通过new的形式执行
//let foo = fn.myBind(obj);
//let res = new foo();
let _this=this instanceof Fn?new fn(...arguments):context
//合并两次参数 例如fn.myBind(obj,1)(2,3,4),吧两个参数合并在一起
return fn.apply(_this,args.concat(...arguments))
}
}
调用:
function foo(a,b,c=0) {
console.log(11)
}
const obj = {
a: 123,
};
//第一种方式
//let fun=foo.myBind(obj,5,6)()
// 通过new 来执行函数
let fun=foo.myBind(obj,5,6)
let res=new fun(7)