简单介绍apply、call、bind方法
apply、call、bind方法的作用是改变函数中this的指向
- apply/call:会自动调用,第一个参数都是设置this的指向,apply第二个参数为数组,call后面传入为参数列表。
- bind:不会自动调用,会返回一个已经绑定好this的函数,传参与call一样
call()方法
/**
* 涉及js的知识点:
* - 原型链:函数的原型链上添加方法
* - 剩余参数接收实参
* - 基本包装类型:非对象类型,通过Object包装
* - this的隐式绑定
*/
//如果没有传入第二个参数,"...args"默认为[]
Function.prototype.myCall = function (thisArg, ...args) {
//1.拿到调用的函数
let fn = this;
//2.对传入的this包装为对象类型“Object(thisArg)”,this为undefined或null,则绑定为window
thisArg = thisArg === null || thisArg === undefined ? window : Object(thisArg);
//3.利用隐式绑定,调用函数
thisArg.fn = fn;
let result = thisArg.fn(...args); //拿到调用后的结果
delete thisArg.fn; // 删除thisArg的fn属性
//4.返回结果
return result;
};
function sum(num1, num2) {
console.log("sum", this);
return num1 + num2;
}
// myCall中的this会被隐式绑定到foo
let result = sum.myCall(123, 1, 2);
console.log(result);
apply()方法
/**
* 涉及js的知识点:
* - es6语法,给参数设置默认值
* - 原型链:函数的原型链上添加方法
* - 剩余参数接收实参
* - 基本包装类型:非对象类型,通过Object包装
* - this的隐式绑定
*/
//如果没有传入第二个参数,args默认为undefined,第十五行“...undefined”会报错,所以要设置默认值为[]
Function.prototype.myApply = function (thisArg, args = []) {
//1.拿到调用的函数
let fn = this;
//2.对传入的this包装为对象类型“Object(thisArg)”,this为undefined或null,则绑定为window
thisArg = thisArg === null || thisArg === undefined ? window : Object(thisArg);
//3.利用隐式绑定,调用函数
thisArg.fn = fn;
let result = thisArg.fn(...args); //拿到调用后的结果
delete thisArg.fn; //调用完后删除这个属性
//5.返回结果
return result;
};
function sum(num1, num2) {
console.log("sum", this);
return num1 + num2;
}
// myApply中的this会被隐式绑定到foo
let result = sum.myApply(123, [1, 2]);
console.log(result);
bind()方法
/**
* 涉及js的知识点:
* - 原型链:函数的原型链上添加方法
* - 剩余参数接收实参
* - 基本包装类型:非对象类型,通过Object包装
* - this的隐式绑定
* - bind设计核心,需要一个代理函数
*/
Function.prototype.myBind = function (thisArg, ...args) {
//1、拿到调用的函数
let fn = this;
//2、对传入的this包装为对象类型,this为undefined或null,则绑定为window
thisArg = thisArg === undefined || thisArg === null ? window : Object(thisArg);
function proxyFn(...laterArgs) {
//3.1 利用隐式绑定给函数绑定this
thisArg.fn = fn;
//3.2 对前面传入的参数和后面传入的参数进行合并传入
let result = thisArg.fn(...args, ...laterArgs);
//3.3 删除thisArg的fn属性
delete thisArg.fn;
//3.4 返回执行后的结果
return result;
}
//3、返回代理函数
return proxyFn;
};
function sum(num1, num2, num3, num4) {
console.log("sum", this);
console.log(num1, num2, num3, num4);
return num1 + num2;
}
let result = sum.myBind("123", 1);
console.log(result(2, 3, 4));
代码中注释有超详细解析,如有不足欢迎补充