日常开发中呢,我们或多或少会用到bind、call、apply这三个方法,今天我们就来讲一讲他们之间的区别和模拟实现解释他的原理;
1.共同点
1.首先这三个方法都是Function原型上的方法,针对函数而言的;
2.其次他们都是用于改变函数的内部this指向,这里划重点:是改变函数执行时候的内部this指向;
3.都是可以接受两个或多个参数,第一个参数就是改变后的this指向,后面为可选参数
2.区别
1.apply和call的调用会立即返回函数执行结果,如果使用apply或call方法,那么this指向他们的第一个参数,apply的第二个参数是一个参数数组,call的第二个及其以后的参数都是数组里面的元素,就是说要全部一一单独列举出来;
func.call(thisOrg,arg1,arg2,.....);
func.apply(thisOrg,[org1,org2,...]);
2.bind不会立即调用,而是返回一个新函数,称为绑定函数,其内的this指向为创建它时传入bind的第一个参数,而传入bind的第二个及以后的参数作为原函数的参数来调用原函数;
此处重点:传入 bind() 方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数
const func = func1.bind(thisOrg,arg1,arg2,...);
const func = func1.bind(thisOrg,[arg1,arg2,...]);
func(arg3,arg4);
call&apply&bind方法的简单实现
call
Function.prototype.call = function(ctx,...args){
// 如果第一个参数为null 或者undefined,则默认指向window
// 这里绑定call方法的this指向
const ctx = ctx || window;
// 将this赋给context的fn属性,此处this是指调用call的function(这话有点绕口自己理解)
// 例如:Array.propotype.slice.call(null,arg1)
// 那么this=Array.propotype.slice
// 同理ctx.fn = Array.propotype.slice;
// ctx.fn的fn里面的this自然指向ctx
ctx.fn = this;
let result;
result = ctx.fn(...args);
delete ctx.fn;
return result;
}
apply
Function.prototype.apply = function(ctx,...args){
const ctx = ctx || window;
ctx.fn = this;
let result;
if(args.length){
result = ctx.fn(...args);
delete ctx.fn;
}else{
result = ctx.fn();
}
return result;
}
bind
Function.prototype.bind = function(ctx){
const _this = this;
var args = [...arguments].slice(1);
return function(){
_this.apply(ctx,args.concat(...arguments))
}
}
这三个函数改变this的指向,关键点在于this的指向的理解,关于js中this的指向,在后续文章中我将和大家探讨一下,敬请关注。