var name ='公众号:前端技术营';var obj ={name:'张三'};functionfn(a, b, c){
console.log(`${a}${b}${c}${this.name}`);};// 模拟callFunction.prototype.myCall=function(){let target = arguments[0]|| window || global
target.fn =thislet args = Array.from(arguments).slice(1)let result = target.fn(...args)delete target.fn
return result
}
fn.myCall(obj,'my','name','is');// my name is 张三
fn.myCall(null,'my','name','is');// my name is 公众号:前端技术营
fn.myCall(undefined,'my','name','is');// my name is 公众号:前端技术营
2.实现apply方法
var name ='公众号:前端技术营';var obj ={name:'张三'};functionfn(a, b, c){
console.log(`${a}${b}${c}${this.name}`);};// 模拟applyFunction.prototype.myApply=function(){let target = arguments[0]|| window || global;
target.fn =this;let args = Array.from(arguments)[1];let result = target.fn(...args);delete target.fn;return result;}
fn.myApply(obj,['my','name','is']);// my name is 张三
fn.myApply(null,['my','name','is']);// my name is 公众号:前端技术营
fn.myApply(undefined,['my','name','is']);// my name is 公众号:前端技术营
3.实现bind方法
var name ='公众号:前端技术营';var obj ={name:'张三'};functionfn(a, b, c){
console.log(`${a}${b}${c}${this.name}`);};// 模拟callFunction.prototype.myBind=function(context){const _this =thisconst args =[...arguments].slice(1);// 返回一个函数returnfunctionF(){// 因为返回了一个函数,我们可以 new F(),所以需要判断if(thisinstanceofF){// 忽略传入的thisreturnnew_this(...args,...arguments)}// 直接调用,将两边的参数拼接起来return_this.apply(context, args.concat(...arguments))}}const fn1 = fn.myBind(obj,'my','name','is');fn1();// my name is 张三const fn2 = fn.myBind(null,'my','name','is');fn2();// my name is 公众号:前端技术营const fn3 = fn.myBind(undefined,'my','name','is');fn3();// my name is 公众号:前端技术营