[英]How can I prepend/append the results of all function calls in JavaScript
可以說我有一個功能
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
基本上,我想給函數調用的每個輸出添加和固定一些固定值,而與函數本身無關。
我嘗試覆蓋valueOf屬性,但是它不起作用
注意: sum
只是一個示例函數。 有沒有可能的解決方案,使其可以使用所有功能?
您可以創建一個原型並使用它來調用函數,並在其中包含所需的任何內容:
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");
如果僅出於登錄目的需要它:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.