1. 程式人生 > 實用技巧 >“函式物件”的屬性length

“函式物件”的屬性length

形參的個數,Rest引數不算。

 1 function ask(question, ...handlers) {
 2   let isYes = confirm(question);
 3 
 4   for(let handler of handlers) {
 5     if (handler.length == 0) {
 6       if (isYes) handler();
 7     } else {
 8       handler(isYes);
 9     }
10   }
11 
12 }
13 
14 // 對於積極的回答,兩個 handler 都會被呼叫
15 //
對於負面的回答,只有第二個 handler 被呼叫 16 ask("are you a pig?", () => alert('You said yes'), result => alert(result));

ask的引數:

  1. 一個字串
  2. 箭頭函式一號
  3. 箭頭函式二號

函式被呼叫時的執行過程:
呼叫confirm函式,顯示一個資訊,根據使用者選擇來返回一個布林值。

把這個布林值交給isYes儲存

用for...of來遍歷handlers陣列

使用者點選確定,isYes值為true,開始遍歷handlers陣列:

先是箭頭函式一號,handler.length==0返回true,因為一號確實沒得引數,所以length是0.

然後檢查isYes的值,一看是true,呼叫箭頭函式一號。

再然後是箭頭函式二號,handler.length==0返回false,因為二號有引數,所以進入else之中,呼叫箭頭函式二號,把true傳遞進去。

使用者點選取消,isYes值為false,開始遍歷hanlers陣列:

先是箭頭函式一號,handler.length==0返回true,因為一號確實沒得引數,所以length是0.

然後檢查isYes的值,一看是false,不了了之,沒有後序。

再然後是箭頭函式二號,handler.length==0返回false,因為二號有引數,所以進入else之中,呼叫箭頭函式二號,把false傳遞進去。