Javascript函数评估


const debugMode = true;
// if "isCritical" is true, display the message regardless of
// the value of debugMode
function logger(message, isCritical) {
if (isCritical) console.log(message);
else if (debugMode) console.log(message);
}

在上面的函数中,如果我发出以下命令,那么UTIL会。检查功能评估";myObj";而不传递数据?我最好不希望UTIL.inspect调用如果";isCritical";设置为false。

logger(
"myObj =n" +
UTIL.inspect(myObj, {
showHidden: false,
depth: null
}),
false
);

当第二个参数为false时,是否有方法避免对函数中的第一个参数求值?

将用于日志记录的代码与是否应该执行它的决定分开。

并使用支持树摇动的构建管道。

rollupjs.org 上的实时示例

// config.js
export const DEBUG = false;
// logging.js
import { DEBUG } from "./config.js";
export const log = console.log; // or whatever
export const debug = DEBUG ? (...args) => logger("debug:", ...args) : () => void 0;
// main.js
import { DEBUG } from "./config.js";
import { log, debug } from "./logging.js";
log("this will always be logged");
if (DEBUG) {
log("This will be eliminated when DEBUG=false")
}
// or more concise:
DEBUG && log(`This can be eliminated ${window.location = "/side-effect"}`);
debug("This approach works for simple things: " + location);
debug(`But it has limits ${window.location = "/side-effect"} :(`);

最新更新