this總是指向調用某個方法的對象,但是使用call()和apply()方法時,就會改變this的指向。
call.(thisOject, arg1 ,arg2 ...)
我們單獨說說call(),因為apply()和call差不多,隻不過apply第二個參數必須傳入的是一個數組,而call 第二個參數可以是任意類型。
obj1.(method).call(obj2,argument1,argument2)
如上,call的作用就是把obj1的方法放到obj2上使用,後面的argument1..這些做為參數傳入。
function add (x, y)
{
console.log (x + y);
}
function minus (x, y)
{
console.log (x - y);
}
add.call (minus , 1, 1); //2
這個例子中的意思就是用 add 來替換 minus ,add.call(minus ,1,1) == add(1,1) ,是以運作結果為:console.log (2); // 注意:js 中的函數其實是對象,函數名是對 Function 對象的引用。
A.call( B,x,y ):就是把A的函數放到B中運作,x 和 y 是A方法的參數。
用call來實作繼承,用this可以繼承myfunc1中的所有方法和屬性。
function myfunc1(){
this.name = 'Lee';
this.myTxt = function(txt) {
console.log( 'i am',txt );
}
}
function myfunc2(){
myfunc1.call(this);
}
var myfunc3 = new myfunc2();
myfunc3.myTxt('Geing'); // i am Geing
console.log (myfunc3.name); // Lee