完整代码
Function.prototype.myBind = function (ctx, ...args) {
const fn = this;
return function (...resArgs) {
if (new.target) {
return new fn(...args, ...resArgs);
}
return fn.apply(ctx, [...args, ...resArgs]);
}
}
function fn(a,b,c,d,e){
console.log(this);
console.log(a,b,c,d,e);
}
const newFn=fn.myBind(1,2,3);
const r=new newFn(3,6,7);
知识详情
- 函数写哪?——写到函数原型上(即
Function.prototype),让所有函数都具有这个方法
- 参数确定:第一个参数接收
this值,然后通过解构收集剩下参数用作参数专递。
- 确定返回内容:需要返回一个新的函数,新的函数内部也会有参数,定义一个新变量
resArgs解构收集
- 绑定this:
- 确定this获取this:调用
newFn时,相当于在调用fn(即第二行代码获取this)。
- 绑定this(即第7行代码)
- 考虑原函数的返回值——需要返回绑定this后的函数。(即第7行代码加上return返回值)
- 考虑调用可能通过new调用——通过
new.target来判断是否通过new调用。
- 如果是new 调用则,
new.target为new的函数
- 否则为undefined