javascript是面向對象的語言,Function也是一種對象,有自己的屬性和方法。call和apply就是js函數自帶方法,掛在Fucntion.prototype上。
一般調用某函數時,直接“函數名(參數)”的寫法即可,函數內部的this指向函數的調用者。
function add(a,b){
console.log(this);
return a+b;
}
add(1,2) // 默認window調用,this指向window
var math = {
add:function(a,b){
console.log(this);
return a+b;
}
}
math.add(1,2) // this指向math
call和apply的作用是給函數重新指定調用者,指定this的指向:
var name = "WINDOW";
var someone = {
name: "yource"
};
/** 一般寫法 **/
function greet1(person) {
var reply = "Hello, " + person.name;
console.log(reply)
}
greet1(someone); // Hello, yource
/** 使用call/apply **/
function greet2() {
var reply = "Hello, " + this.name;
console.log(reply)
}
greet2(); // Hello, WINDOW
greet2.call(someone); // Hello, yource
greet2.apply(someone); // Hello, yource
call和apply的不同之處僅在於提供參數的方式:call使用一組參數列表,apply使用參數數組。
/*apply()方法*/ function.apply(thisObj[, argArray]) /*call()方法*/ function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);
apply最多只能有兩個參數:調用者thisObj和一個數組argArray。call可以接受多個參數,第一個參數與apply一樣,后面則是一串參數列表。
