call
Function.prototype.myCall = function(){ const fn = Symbol('fn'); const [p, ...arg] = arguments; let undertake = p || window; undertake[fn] = this; const result = undertake[fn](...arg); delete undertake[fn]; return result;}const o = { name:"张三"}function test(name){ console.log(this, name)}test.myCall(o,'张三')
bind
Function.prototype.myBind = function(){ const fn = Symbol("fn") const [p, ...arg] = arguments; const _o = p || window; _o[fn] = this; return function(){ const result = _o[fn](...[...arg, ...arguments]); delete _o[fn]; return result; }}const o = { name:"张三"}function test(name,age){ console.log(this, name, age)}let fn = test.myBind(o,'张三')(18)
apply
Function.prototype.myApply = function(){ const fn = Symbol('fn'); const [p, arg] = arguments; const _o = p || window; _o[fn] = this; const result = _o[fn](...arg); delete _o[fn]; return result;}const o = { sex:"0"}function test(name,age){ console.log(this,name,age)}test.myApply(o,['zs',18])