call
Function.prototype.mycall = function(context, ...args) { if (this === Function.prototype) { return undefined; } context = context || window; const fn = Symbol(); context[fn] = this; // this就是 调用的函数 const result = context[fn](...args); // delete context[fn]; return result; }
实现逻辑如下,把函数给这个对象,然后通过对象的方式调用,this 就指向这个 对象了
function test(...args) { console.log(this.name, ...args); } let obj = { name: 'lisi' } obj.fn = test; obj.fn(1,2);
apply 只是参数处理不一样
Function.prototype.myapply = function(context, args = []) { if (this === Function.prototype) { return undefined; } context = context || window; const fn = Symbol(); context[fn] = this; // this就是 调用的函数 const result = context[fn](...args); // delete context[fn]; return result; }
bind
Function.prototype.mybind = function(context, ...args) { if (this === Function.prototype) { return undefined; } if (!context) { return this; } const fun = this; return function(...args1) { return fun.call(context, ...[...args,...args1]); // 或者如下 // const fn = Symbol(); // context[fn] = fun; // const result = context[fn](...[...args,...args1]); // delete context[fn]; // return result; }; }