call apply bind
在JS中,这三者都是用来改变函数的this对象的指向的,他们有什么样的区别呢。 在说区别之前还是先总结一下三者的相似之处:
1、都是用来改变函数的this对象的指向的。
2、第一个参数都是this要指向的对象。
3、都可以利用后续参数传参。
由于都是对函数作用的属性,所以封装方法时都是放在了Function的原型上。
call
call可以让函数执行,并且可以改变函数执行时内部的this指向,this指向了call的第一个实参,call后边的所有参数都被作为实参传给了前边到的函数。
call的封装方法:myCall
Function.prototype.myCall = function myCall(context, ...arg) {
context = context || window;
let a = Symbol();
context[a] = this;
let res = context[a](...arg);
delete context[a];
return res;
}
apply
apply功能类似于call,但是第二个参数是个数组或者类数组的集合,虽然是以一个集合的形式传过去的,但是接收时还是散乱的接收的。
apply的封装方法:myApply
Function.prototype.myApply = function myApply(context, arg) {
arg = arg || [];
context = context || window;
let a = Symbol();
context[a] = this;
let res = context[a](...arg);
delete context[a];
return res;
}
bind
bind用法跟call一样,bind返回值是一个新函数,新函数执行时fn才会执行,fn中的this这时才会被改成新的指向。
bind的封装方法:myBind
Function.prototype.myBind = function (context, ...arg) {
var _this = this;
return function (...ary) {
return _this.apply(context, arg.concat(ary))
}
}