跳到內容

JavaScript/閉包/練習

來自維基文庫,開放世界的開放書籍

主題:閉包



1. 編寫一個指令碼建立一個可引數化的函式 decoratorFactory。它接受一個字串,用給定的引數“裝飾”日誌資訊。例如: const tiny = decoratorFactory("日誌訊息來自子例程 'someTinyAction': "); alert(tiny("除以零。"));。該指令碼內部應使用閉包。

單擊檢視解決方案
"use strict";

function decoratorFactory(someText) {
  // 'someText' is known in 'decoratorFunction' as well as in 'logFunction'
  const logFunction = function (message) {
    // use 'someText' from the outer lexical environment and the function's parameter 'message'
    return(someText + ": " + message) // maybe: plus timestamp, ...
  }
  return logFunction;
}

const computeMsg = decoratorFactory("Log message from subroutine 'computeAverage'");
alert(computeMsg("Division by zero."));

const main = decoratorFactory("*** Log message from 'main'");
alert(main("No database connection."));

alert(main("Unknown system error."));
華夏公益教科書