1.介绍
在JavaScript中,call、apply和bind是Function对象自带的三个方法,这三个方法的主要作用是改变函数中的this指向。
call、apply、bind方法的共同点和区别:
apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文(函数的每次调用都会拥有一个特殊值——本次调用的上下文(context)——这就是this关键字的值。);
apply 、 call 、bind 三者都可以利用后续参数传参;
bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。
解释-apply
apply() 方法调用一个具有给定 this 值的函数,以及以一个数组(或一个类数组对象)的形式提供的参数。
尝试一下
const numbers = [5, 6, 2, 3, 7];
const max = Math.max.apply(null, numbers);
console.log(max);
// Expected output: 7
const min = Math.min.apply(null, numbers);
console.log(min);
// Expected output: 2
返回值
调用有指定 this 值和参数的函数的结果。
解释-bind
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
尝试一下
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// Expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// Expected output: 42
返回值
返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。
解释-call
call() 方法使用一个指定的 值和单独给出的一个或多个参数来调用一个函数。
尝试一下
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name);
// Expected output: "cheese"
返回值
使用调用者提供的 值和参数调用该函数的返回值。若该方法没有返回值,则返回 undefined
2.总结:
一开始我对它们不是很了解,感觉有点绕,最后多看了几遍,然后结合代码和概念,才明白了它们的用法。作为小白,只有不断积累才能丰富自己,欢迎前辈们指教!!!!
自勉:人生像激流中行驶的帆船,必定会有奋斗,为了战胜激流而奋斗,而“激流”代表的则是理想。