call、apply、bind

2023/7/25

# 异同

首先,call apply bind三个方法都可以用来改变函数的this指向,具体区别如下:

1、fn.call (newThis,params) call函数的第一个参数是this的新指向,后面依次传入函数fn要用到的参数。会立即执行fn函数。

2、fn.apply (newThis,paramsArr) apply函数的第一个参数是this的新指向,第二个参数是fn要用到的参数数组,会立即执行fn函数。

3、fn.bind (newThis,params) bind函数的第一个参数是this的新指向,后面的参数可以直接传递,也可以按数组的形式传入。 不会立即执行fn函数,且只能改变一次fn函数的指向,后续再用bind更改无效。返回的是已经更改this指向的新fn

# 实现:

//call
Function.prototype.mycall = function(target,...args){
	target = target || window;
    const targetKey = symbol();
    target[targetkey] = this;
    const res = target[targetkey].(...args);
    delete target[targetkey]
    return res
}
//apply
Function.prototype.mycall = function(target,args){
	target = target || window;
    const targetKey = symbol();
    target[targetkey] = this;
    const res = target[targetkey].(...args);
    delete target[targetkey]
    return res
}
//bind
Function.prototype.mycall = function(target,...args){
	target = target || window;
    const targetKey = symbol();
    target[targetkey] = this;
    const res = target[targetkey].(...args);
    delete target[targetkey]
    return res
}