call 和 apply 都是爲了動態改變某個函數運行時的上下文而存在的,即改變函數體內部 this 的指向。call 和 apply 主要的區別在於他們的聲明方式不同。call 需要參數分開傳遞,而 apply 需要傳入由參數組成的數組。
ep:
function people() {}
people.prototype = {
say: function() {
alert("hell word");
}
}
var student = new people();
student.say(); //hello world
student2 = {}; //沒有say()方法
student.say.call(student2); //hello world
studnet.say.apply(student2); //此時的student2可以使用say()方法
(1).傳遞參數
ep:
function sum(x,y) {
return x+y;
}
function call1(num1,num2) {
return sum.call(this,num1,num2);
}
function apply1(num1,num2) {
return sum.apply(this,[num1,num2]); //參數爲數組形式
}
(2).改變函數運行的作用域
window.color = 'red';
var obj = {color: 'blue'};
function showColor() {
alert(this.color);
}
showColor.call(this); //red
showColor.call(obj); //blue