JavaScript/闭包/练习
外观
< 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."));