《JavaScript進階程式設計》裡對 call() 和 apply() 的解釋 (116頁)

來源:互聯網
上載者:User

標籤:相同   call()   log   apply()   rip   執行環境   函數   方法   範圍   

每個函數都包含兩個非繼承而來的方法:apply()和call()。這兩個方法的用途都是在特定的範圍中調用函數,實際上等於設定函數體內this對象的值。

apply():

方法接受兩個參數:一個是在其中運行函數的範圍,另一個是參數數組。其中,第二個參數可以是Array的執行個體,也可以是arguments對象。例如:

function sum(num1, num2) {  return num1 + num2;}function callSum1(num1, num2) {  return sum.apply(this, arguments); //傳入arguments對象}function callSum2(num1, num2) {  return sum.apply(this, [num1,num2]); //傳入數組}alert(callSum1(10, 10));alert(callSum2(10, 10));

在上面的例子中,callSum1()在執行 sum() 函數時傳入了 this 作為 this 值(因為是在全域範圍中調用的,所以傳入的就是 window 對象)和 arguments 對象。

 

call():

call() 方法與 apply() 方法的作用相同,它們的區別僅在於接受的參數不同。對於 call() 方法而言,第一個參數是 this 值沒有變化,變化的是其餘參數都直接傳遞給函數。換句話說,在使用 call() 方法時,傳遞給函數的參數必須逐個列出來,如下面的例子所示。

function sum(num1, num2) {  return num1 + num2;}function callSum(num1, num2) {  return sum.call(this, num1, num2);}alert(callSum(10, 10));

 

事實上,傳遞參數並非 apply() 和 call() 真正的用武之地;它們真正強大的地方是能夠擴充函數賴以運作的範圍。下面來看一個例子。

window.color = ‘red‘;var o = {  color: ‘blue‘};function sayColor() {  alert(this.color);}sayColor(); //bluesayColor.call(this); //blue sayColor.call(window); //bluesayColor.call(o); //red

當運行 sayColor.call(o)時,函數的執行環境就不一樣了,因為此時函數體內的 this 對象指向了 o 中,然後再通過 o 來調用它的。

《JavaScript進階程式設計》裡對 call() 和 apply() 的解釋 (116頁)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.