改变this指向的三大方法
原理
都是在需要绑定的上下文中添加一个函数,执行函数,删除函数,返回结果。
call
Function.prototype.xf_call = function (thisArg, ...args) {
const fn = this
thisArg = thisArg || window
const key = Symbol()
thisArg[key] = fn
const result = thisArg[key](...args)
delete thisArg[key]
return result
}
apply
Function.prototype.xf_apply = function (thisArg, args) {
if (args instanceof Array) {
const fn = this
thisArg = thisArg || window
const key = Symbol()
thisArg[key] = fn
const result = thisArg[key](args)
delete thisArg[key]
return result
}
throw new Error('apply args must be get a arr')
}
bind
Function.prototype.xf_bind = function(thisArg, ...args) {
const fn = this
thisArg = thisArg || window
const key = Symbol()
thisArg[key] = fn
return function () {
const result = thisArg[key](...args)
delete thisArg[key]
return result
}
}
function a () {
let name = '牛总'
console.log('a 函数的 this', this);
}
const obj = {
age: 18
}
console.log('a.xf_call(obj, 1, 2, 3)', a.xf_bind(obj, [1, 2, '天涯路尽'], 'i love you')());
console.log('a.xf_call(obj', a.xf_bind(obj, ['天涯路尽'])());