在开始之前,我们先了解什么是apply、call、bind
[MDN关于call的解释](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call)
作用就是:能够改变函数运行时上下文(ctx),函数在运行时会创建执行上下文中(js代码执行的抽象环境),上下文存在this,vo变量对象,scope-chain作用域链。
注意:this
是函数运行时确定的。
使用场景:在一个类数组中,通过call改变运行上下文,转换成数组;
伪代码
//使用call改变数组原型方法的this指向
const array = Array.prototype.slice.call(arguments);
// this总是指向调用它的对象
Array.prototype.slice = function(){
//此时slice方法中this的值也就是arguments
const arr = this;
let Array = []
for(const i = 0;i<arr.length;i++)
//slice通过遍历 返回新数组对象
Array.push(arr[i])
}
return Array;
示例
function bar(a,b,c){
const bool = arguments instanceof Array;//false
const array = Array.prototype.slice.call(arguments);
console.log(array) //[1,2,3]
}
bar(1,2,3)
1、call
Function.prototype.myCall = function(self,...args){
// self 需要绑定的函数执行上下文对象
self = self !== undefined && self !== null ? Object(self) : window;
// this指向bar函数,因为this总是指向调用它的对象。
self.fn = this;
//执行该方法,接收参数
const ret = self.fn(...args);
delete self;
return ret //返回结果
}
// 例子
function bar(a,b){
console.log(this) // this: window
return a+b
}
const a = bar.myCall(null,1,2);// this: Window
console.log(bar.call(null, 1, 2))// this:Window
console.log(a)
2、apply
实现方式与call类似,只是传递的参数是数组
Function.prototype.myApply = function(self,args=[]){
self = self !== undefined && self !== null ? Object(self) : window;
self.fn = this;
const ret = self.fn(...args);
delete self;
return ret
}
function bar(a,b) {
console.log(this)
return a + b
}
const a = bar.myApply(null, [1, 2]); //this:String {'', fn: ƒ}
console.log(bar.apply(null, [1, 2]))//this: Window
console.log(a)
3、bind
- bind方法的参数作为新函数的this指向
- bind方法执行后创建一个新函数,执行新函数得到绑定this后的执行结果
Function.prototype.myBind = function(self){
self = self !== undefined && self !== null ? Object(self) : window;
self.fn = this;
function proxy(...args){
const ret = self.fn(...args);
delete self;
return ret;
}
return proxy
}
function bar(a,b) {
console.log(this)
return a + b
}
const a = bar.myBind(1)(1,2);// this:Number
console.log(bar.bind(null)(1, 2)) //this: Window
console.log(a)// 3