Effective JavaScript Item 24 使用一個變數來儲存arguments的引用

來源:互聯網
上載者:User

Effective JavaScript Item 24 使用一個變數來儲存arguments的引用

本系列作為Effective JavaScript的讀書筆記。

假設需要一個API用來遍曆若干元素,像下面這樣:


var it = values(1, 4, 1, 4, 2, 1, 3, 5, 6);it.next(); // 1it.next(); // 4it.next(); // 1

相應的實現可以是:


function values() {var i = 0, n = arguments.length;return {hasNext: function() {return i < n;},next: function() {if (i >= n) {throw new Error("end of iteration");}return arguments[i++]; // wrong arguments}};}

但是執行的實際情況卻是:


var it = values(1, 4, 1, 4, 2, 1, 3, 5, 6);it.next(); // undefinedit.next(); // undefinedit.next(); // undefined

原因在於:對於arguments對象的賦值是隱式完成的。

在next方法內部,使用了arguments,然而此arguments和values方法開始處的arguments並不是一個對象。

解決方案也很簡單,就是將需要訪問的arguments使用另外一個變數進行引用。然後通過閉包的性質在其嵌套的函數中進行訪問就可以了,像下面這樣:


function values() {var i = 0, n = arguments.length, a = arguments;return {hasNext: function() {return i < n;},next: function() {if (i >= n) {throw new Error("end of iteration");}return a[i++];}};}var it = values(1, 4, 1, 4, 2, 1, 3, 5, 6);it.next(); // 1it.next(); // 4it.next(); // 1

總結:

  1. 當在嵌套的函數中使用arguments時,注意arguments的實際指向
  2. 需要在嵌套的函數中使用外部函數的arguments時,將外部函數的arguments對象儲存到一個變數中,讓嵌套函數進行訪問

聯繫我們

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