call()方法和apply()方法的作用相同,他們的區(qū)別在于接收參數(shù)的方式不同尊搬。
對于call()叁鉴,第一個參數(shù)是this值沒有變化,變化的是其余參數(shù)都直接傳遞給函數(shù)佛寿。(在使用call()方法時幌墓,傳遞給函數(shù)的參數(shù)必須逐個列舉出來。使用apply()時冀泻,傳遞給函數(shù)的是參數(shù)數(shù)組)如下代碼做出解釋:
function add(c, d){
return this.a + this.b + c + d;
}
var o = {a:1, b:3};
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34