function bindThis(f, oTarget) { return function () { return f.call(oTarget, ...arguments) } } function bindThis(f, oTarget) { return function () { return f.apply(oTarget, [...arguments]) } } function bindThis(f, oTarget) { return f.bind(oTarget) }
function bindThis(f, oTarget) { return f.bind(oTarget) || function() { return f.apply(oTarget,arguments) || f.call(oTarget, ...arguments);}; }
function bindThis (f, oTarget) { return f.myCall(oTarget, 1) } Function.prototype.myCall = function (context) { let ctx = Object(context) || globalThis let args = [] // 遍历arguments for (let i = 1; i < arguments.length; i++) { args.push('arguments[' + i + ']') } // 利用obj隐式绑定规则 ctx.fn = this let result = eval('ctx.fn(' + args + ')') delete ctx.fn return result } Function.prototype.myApply = function (context, arr) { let ctx = Object(context) || globalThis let result ctx.fn = this let args = [] if (!arr) { result = ctx.fn() } else { for (let i = 0; i < arr.length; i++) { args.push('arr[' + i + ']') } result = eval('ctx.fn(' + args + ')') } delete ctx.fn return result } Function.prototype.myBind = function (context, ...args) { const fnToBind = this const fBound = function () { let concatArgs = args.concat(...arguments) return fnToBind.apply(this instanceof fBound ? this : context, concatArgs) } fBound.prototype = Object.create(fnToBind.prototype) fBound.prototype.contructor = fBound return fBound }
function bindThis(f, oTarget) { oTarget.p = f return function fun(){ return oTarget.p(...arguments) } }