改变函数的this指向方法
1、call函数
/**
* 功能
* 1、接收到参数
* 2、绑定this
* 3、保留返回的内容
*/
Function.prototype.myCall = function () {
const self = this;
// console.log('this',this)
// const args1 = [...arguments]
const args = Array.prototype.slice.call(arguments)
// console.log('args',args)
// console.log('args1',args1)
// _this就是改变之后的this
const _this = args.shift()
// console.log('_this',_this)
_this.fn = self
// 执行原本的参数
const res = _this.fn(...args)
delete _this.fn
return res;
}
2、apply函数
Function.prototype.myApply = function () {
const self = this;
// 只有一个参数或者两个,第二个是数组
const _this = arguments[0];
console.log('_this',_this)
_this.fn = self;
let result;
if (arguments[1]){
result = _this.fn(...arguments[1])
}else {
result = _this.fn()
}
delete _this.fn;
return result;
}
3、bind函数
/**
* 1、改变this指向
* 2、bind后面第一个参数是this的值,后面的参数是函数接收的参数的值
* 3、返回值不变(return)
*/
// 定义的地方在函数的原型上
Function.prototype.myBind = function () {
// this的指向是原函数
const self = this;
// 获取传入的参数值
// 原本的arguments得到的是一个伪数组,需要转化为真正的数组
const args = Array.prototype.slice.call(arguments);
// pop出第一个数,取出this
const thisValue = args.shift()
return function () {
// 返回执行函数
return self.apply(thisValue,args);
}
}
4、区别
- call和apply都是定义即执行,但是bind定义之后要被调用才执行
- call和bind传入的是参数列表,但是apply传入的参数是以数组的形式