虽然在实际项目中我都没有用过这两个方法,但是最近在回顾 JS 知识点的时候又碰到了它们,所以想记录一下。
首先:call 和 apply
都是为了解决改变 this
的指向,作用都是相同的。
function check(){
console.log("this::", this);
console.log("this.a::", this.a);
}
var s = {a: 1, b: 2}
check(); // this:: window // this.a:: undefined
check.call(s); // this:: {a: 1, b: 2} // this.a:: 1
check.apply(s); // this:: {a: 1, b: 2} // this.a:: 1
其次:call
和 apply
传参的方式不同。两者的第一个参数传入的都是 this 将要指向的对象(例中的 s 就是)。除了第一个参数外,call
可以接收一个参数列表,apply
只接收一个参数数组。
function add(c, d){
return this.a + this.b + c + d;
}
var s = {a: 1, b: 2}
add(); // NaN
add.call(s, 3, 4); // 10
add.apply(s, [3, 4]); // 10