【问题标题】:Add a logging to store info about users actions JavaScript添加日志以存储有关用户操作 JavaScript 的信息
【发布时间】:2020-07-08 23:41:19
【问题描述】:

我为此创建了一个函数。也许存在更好的解决方案?

function writeLog(operationIdentifier, prevResult, operationNumber, newResult) {
const logEntry = {
    operation: operationIdentifier,
    prevResult: prevResult,
    number: operationNumber,
    result: newResult,
};
logEntries.push(logEntry);
console.log(logEntries);

从这里:

function add() {
    const enteredNumber = getUserNumberInput();
    const initialResult = currentResult;
    currentResult += enteredNumber;
    createAndWriteOutput('+', initialResult, enteredNumber);
    writeLog('ADD', initialResult, enteredNumber, currentResult);
}

【问题讨论】:

标签: javascript


【解决方案1】:

您可以尝试使用代理进行日志记录

const increment = a => a + 1;

const proxy = new Proxy(increment, {
  apply(target, thisArg, args) {
    console.log(`Incrementing the value "${args[0]}"`);
    const result = target(...args);
    console.log(`Result: "${result}"`);
    return result;
  },
});

increment(5); 
/* nothing logs here */

proxy(5);
/* Incrementing the value "5".
Result: "6" */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 2015-10-10
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多