1.call, apply和bind的用法
call, apply, bind都是用来改变this的指向
apply接收两个参数,第一个参数是`this`的指向,第二个参数是函数接收的参数,以数组的形式进行传递
call第一个参数也是用来改变`this`的指向,后面的参数均是函数接收的参数
**apply与call均只改变this的指向一次**
bind第一个参数也是改变`this`的指向,后面与call类似也是传入参数列表,但与call不同的是,bind的可以不需要一次性传入所有参数,并且bind改变`this`指向后不会立即执行而是返回一个永久改变`this`指向的函数
三者的区别:
(1). 都可以改变`this`的指向;
(2). 第一个参数都是`this`要指向的对象;
(3). 三个都可以传参,但是方法各不相同,apply是数组,bind和call都是利用参数列表进行传参但是bind可以分多次传参,call只可以传一次;
(4). bind是返回绑定`this`之后的函数,apply和call是立即调用
2.call,apply,bind的手写
Function.prototype.myCall = function () {
let context = arguments[0] || window;
context.fn = this;
let args = [...arguments].slice(1);
let result = context.fn(...args);
delete context.fn;
return result;
}
Function.prototype.myApply=function(){
let context=arguments[0]||window;
context.fn=this;
let result;
if(arguments[1]) result=context.fn(...arguments[1]);
else return context.fn();
delete context.fn;
return result;
}
Function.prototype.myBind=function(){
let context=arguments[0]||window;
var self=this;
var args = Array.prototype.slice.call(arguments, 1);
var foo= function(){
var bindArgs=Array.from(arguments);
self.apply(this instanceof self?this:context ,args.concat(bindArgs));
}
foo.prototype=this.prototype;
return foo;
}
参考链接:
用call或bind实现bind() - 会开花的小胡杨 - 博客园 www.cnblogs.com/MelodysBlog…
JavaScript深入之call和apply的模拟实现 juejin.cn/post/684490…