call,apply,bind简单实现
const log = console.log.bind(this)
const obj = {
val: '这是call'
}
function fn(B, X) {
return {
b: B,
a: this.val,
x: X
}
}
call
Function.prototype.calll = function (target) {
const fn = Symbol('fn')
target[fn] = this
const args = [...arguments].slice(1)
const ret = target[fn](...args)
delete target[fn]
return ret
}
const res1 = fn.calll(obj, '这是B')
log('res1', res1) //{b: '这是B', a: '这是call', x: undefined}
apply
Function.prototype.applyy = function (target) {
const fn = Symbol('fn')
target[fn] = this
const args = [...arguments]?.[1]
const ret = target[fn](...args)
delete target[fn]
return ret
}
const res2 = fn.applyy(obj, ['这是B'])
log('res2', res2) //{b: '这是B', a: '这是call', x: undefined}
bind
Function.prototype.bindd = function (target) {
const self = this
const args = Array.prototype.slice.call(arguments, 1)
function func() {
const newArgs = Array.prototype.slice.call(arguments)
return self.apply(this instanceof func ? func : target, args.concat(newArgs))
}
func.prototype = Object.create(this.prototype) // new出来的实例可以继承绑定函数的方法
return func
}
const Res = fn.bindd(obj, '这是B')
const ret = new Res('这是X')
log('call', ret) //{b: '这是B', a: undefined, x: '这是X'}