javascript Call方法 的使用,javascriptcall

來源:互聯網
上載者:User

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
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.