如何在JavaScript中预先添加/附加所有函数调用的结果

问题描述 投票:0回答:2

让我们说我有一个功能

function sum(...args) { return args.reduce((acc, v) => acc + v, 0) }

我正在使用它 - >

console.log( “hi ” + sum(2,3) + “ hello” )会给我输出hi 5 hello

我想达到hi start 5 end hello的结果

基本上,我想在函数调用的每个输出中追加和前置一些固定值,而不管函数本身如何。

我试过覆盖属性的值,但它不起作用

注意:sum只是一个示例函数。是否有可能的解决方案,以便它适用于所有功能?

javascript function append prepend
2个回答
0
投票

您可以创建一个原型并使用它来调用您的函数,并在其中包含您想要的任何内容:

Function.prototype.debug = function(...args){
    let res = this.apply(this, args);
    console.log("Called function '" + this.name + "'. Result: start " + res + " end");
    return res;
}

function sum(...args) {
   return args.reduce((acc, v) => acc + v, 0)
}

console.log( "hi " +  sum.debug(2,3) + " hello");

0
投票

如果您只需要它用于记录目的:

function sum(a, b) {
  return a + b;
}

function divide(a, b) {
  return a/b;
}

const oldLog = console.log;
console.log = function(msg) {
  oldLog(`start ${msg} end`);
}

console.log(sum(1,2));
console.log(divide(1,2));
© www.soinside.com 2019 - 2024. All rights reserved.