call
// call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
// 修改this指向, 相当于给ctx新增一个函数(this指向的函数), 函数可以引用ctx的属性
Function.prototype._call = function (ctx = window, ...args) {
ctx.fn = this
const result = ctx.fn(...args)
delete ctx.fn
return result
}
const obj = {
name: '11',
fun() {
console.log(this.name);
}
}
const obj2 = { name: '22' }
obj.fun() // 11
obj.fun.call(obj2) // 22
obj.fun._call(obj2) // 22
apply
// apply() 方法使用一个指定的 this 值和单独给出的一个或多个数组参数来调用一个函数。
Function.prototype._apply = function (ctx, args) {
ctx.fn = this
const result = ctx.fn(...args)
delete ctx.fn
return result
}
const obj = {
name: '11',
fun() {
console.log(this.name);
}
}
const obj2 = {name: '22'}
obj.fun() // 11
obj.fun.apply(obj2) // 22
obj.fun._apply(obj2) // 22
bind
// bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
Function.prototype._bind = function (ctx, ...args) {
const _self = this
const bindFn = (...reset) => {
return _self.call(ctx, ...args, ...reset)
}
return bindFn
}
const obj = {
name: '11',
fun() {
console.log(this.name);
}
}
const obj2 = {name: '22'}
obj.fun()
const fn = obj.fun.bind(obj2)
const fn2 = obj.fun._bind(obj2)
fn() // 22
fn2() // 22