1.call
Function.prototype.myCall = function(context = window,...args) {let fn = this,res = null;context.$fn = fn;res = context.$fn(...args);delete context.$fn;return res;}
注意:一个call是让左边函数执行(this是传递的参数),多个call是让最后传参的函数执行(this是window/undefined)
function fn1(){ console.log(1) }function fn2(){ console.log(2) }fn1.call(fn2)fn1.call.call(fn2)Function.prototype.call(fn1)Function.prototype.call.call(fn1)//输出结果://1 2 无输出 1
2.apply
Function.prototype.myApply = function(context = window,args) {let fn = this,res = null;context.$fn = fn;res = context.$fn(...args);delete context.$fn;return res;}
3.bind
Function.prototype.myBind = function(context = window,...outerArg) {let fn = this,fnNOP = function(){};context.$fn = fn;let fnBound = function(...innerArgs) {res = fn.apply(this instanceof fn ? this : context,outerArgs.concat(innerArgs))}fnNOP.prototype = fn.prototype;fnBound.prototype = new fnNOP();return fnBound;}
