返回
手写call、bind、apply,算法学习的必由之路
前端
2023-10-13 02:27:12
call、bind、apply简介
call
call方法用于调用一个函数,并指定该函数的执行上下文,即this指向的对象。call方法接受两个参数,第一个参数是指定this指向的对象,第二个参数及以后的参数是传递给该函数的参数。
bind
bind方法与call方法类似,也是用于调用一个函数,并指定该函数的执行上下文,但bind方法返回一个新的函数,而不是立即调用该函数。bind方法接受两个参数,第一个参数是指定this指向的对象,第二个参数及以后的参数是传递给该函数的参数。
apply
apply方法与call方法类似,也是用于调用一个函数,并指定该函数的执行上下文,但apply方法接受的参数列表与call方法不同。apply方法接受两个参数,第一个参数是指定this指向的对象,第二个参数是一个数组,其中包含传递给该函数的参数。
call、bind、apply实现
下面,我们来看看call、bind、apply三个函数的手写实现。
call实现
Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error: Function.prototype.myCall can only be called on functions.');
}
const args = [];
for (let i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
};
bind实现
Function.prototype.myBind = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error: Function.prototype.myBind can only be called on functions.');
}
const args = [];
for (let i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
const fn = this;
return function() {
const args2 = [];
for (let i = 0; i < arguments.length; i++) {
args2.push(arguments[i]);
}
return fn.apply(context, args.concat(args2));
};
};
apply实现
Function.prototype.myApply = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error: Function.prototype.myApply can only be called on functions.');
}
const args = [];
if (arguments[1]) {
for (let i = 0; i < arguments[1].length; i++) {
args.push(arguments[1][i]);
}
}
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
};
总结
call、bind、apply三个函数都是JavaScript中的重要函数,它们可以改变函数的执行上下文,从而实现对象方法的调用、函数柯里化、函数借用等功能。作为一名JavaScript开发者,掌握这三个函数的手写实现是必不可少的。
本文介绍了call、bind、apply的基本概念及手写实现,希望对你有所帮助。如果你想了解更多关于call、bind、apply的知识,可以继续学习以下内容: