跳到内容

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."));
华夏公益教科书