javascript Call方法 的使用,javascriptcall
call 的意思是把 animal 的方法放到cat上執行,原來cat是沒有showName() 方法,現在是把animal 的showName()方法放到 cat上來執行,所以this.name 應該是 Cat
function Animal(){
this.name = "Animal";
this.showName = function(){
alert(this.name);
} ;
}
function Cat(){
this.name = "Cat";
}
var animal = new Animal();
var cat = new Cat();
animal.showName.call(cat,",");
教javascript中call的問題
使用call和apply方法,主要是為了修改函數運行時的this指標。
將你的代碼修改下,就知道區別了:
var each = function(array, fn){ for(var index in array){ // 這裡使用 // fn(index, array[index]) 形式或 // fn.call(null, index, array[index]) 或 // fn.apply(null, index, array[index]) // 函數內部的this都是指向window // 而當你想要修改this的時候,就知道call、apply與直接加括弧調用的區別了 fn.call(array[index], index, array[index]); }};// 這裡可以直接使用 this 來取得當前遍曆的元素each([4, 20, 3], function(){ alert(this);});// 這裡使用就沒什麼區別了each([4, 20, 3], function(index, elem){ alert(elem);});
參考地址:www.w3school.com.cn/...ng.asp
對於javascript 中的call函數的理解問題
標準解釋:call方法是將一個對象的方法在另一個對象的上下文環境中執行。
詳細解釋:你的例子中,myFun.call(myObject, 13, 3, 95)執行時是這樣的:
1. 調用myFun函數
2. 將13,3,95三個參數傳遞給它(你的myFun方法中沒有處理這些參數的代碼,所以傳了也沒有用)
3. 將myFun函數中的所有this用myObject代替(同樣,你的myFun函數中沒有使用this,所以執行結果和直接調用myFun()是一樣的)
修改一下你的例子,協助你理解:
function myFun(p1, p2, p3)
{
this.para1 = p1;
this.para2 = p2;
this.para3 = p3;
}
var myObject = new Object();
alert(myObject.para1) //顯示undefined
myFun.call(myObject,13,3,95); /*執行的時候,myFun方法中的this全部用myObject對象代替,所以在這個例子中,執行myFun方法和直接寫下面的語句效果是一樣的:
myObject.para1 = 13;
myObject.para2 = 3;
myObject.para3 = 95;
*/
alert(myObject.para1) //顯示13