本文最后更新于 2024-03-23T16:32:38+00:00
它们的作用都是改变 this 指向
call:fn.call(obj, args1, args2, args3...)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| Function.prototype.newCall = function(context, ...args) { context = context || window
const fn = this
const key = Symbol('context-key') context[key] = fn const result = context[key](...args)
delete context[key]
return result
}
function fn(callName, callFnName) { console.log(callName) console.log(callFnName) console.log(this.name) }
fn.newCall({ name: '张三' }, '张三 call 的', 'newCall')
|
那对应的 apply,只需要更改下函数定义参数的写法
fn.apply(obj, [args1, args2, args3...])
1 2 3 4 5 6 7 8 9 10 11
| Function.prototype.newApply = function(context, args) { }
fn.newApply({ name: '张三' }, ['张三 apply 的', 'newApply'])
|
那对应的 bind 本质可以借助上面的call/apply
实现
fn.bind(obj, args1, args2, args3...)()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| Function.prototype.newBind = function(context, ...args) { context = context || window
const fn = this
return function(..._args) { return fn.newApply(context, args.concat(_args)) } }
function fn(callName, callFnName) { console.log(callName) console.log(callFnName) console.log(this.name) }
const bindFn = fn.newBind({ name: '张三' }, '张三 bind 的', 'newBind') bindFn()
|