我創建了一個函式包裝器來幫助我提供各種列印陳述句:
function fnWrapper(fn, verbosity=false) {
return function(...rest) {
if (verbosity) console.log(`Calling "${fn.name}(${rest})"`)
const res = fn(...rest); // possible to add debugging **within** this wrapped function?
if (verbosity) console.log('==>', res)
return res;
}
}
function add(x,y) {
return x===0 ? y : add(x-1, y 1);
}
const add2 = fnWrapper(add, true);
add2(2,3);
// Calling "add(2,3)"
// ==> 5
是否可以在函式本身中添加除錯,例如,在最基本的情況下翻譯如下函式:
function something(x,y) {
console.log(arguments); // add this in
...
}
所以對于上面的函式,它會add變成:
function add(x,y) {
console.log(arguments);
return x===0 ? y : add(x-1, y 1);
}
如果是這樣,那該怎么做?
uj5u.com熱心網友回復:
不,這是不可能的,你不能改變函式的作用。
問題是add呼叫add,add2也add只呼叫。但是,您可以簡單地替換 add:
function fnWrapper(fn, verbosity=false) {
return function(...rest) {
if (verbosity) console.log(`Calling "${fn.name}(${rest})"`)
const res = fn.call(this, ...rest);
if (verbosity) console.log('==>', res)
return res;
}
}
function add(x,y) {
return x===0 ? y : add(x-1, y 1);
}
add = fnWrapper(add, true); /*
^^^ */
add(2,3);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/473268.html
標籤:javascript 递归
下一篇:改進遞回函式的除錯輸出
