自定义函数名称和参数(例如在`.getString()`中)



tl;博士:

我想编辑函数的外观。例如,当您在Firefox或Chrome中使用console.log时,我想编辑我们看到的参数和名称,并编辑.length.name属性。这可能吗?

较长的版本:

我想通过在前面和后面添加指令来复制和自定义给定函数的执行。我的代码如下:

function customizeFunction(funcToCustomize) {
return function(...args) {
// Some instructions, for example :
console.log('Calling', funcToCustomize.name);
// The function itself
let returnValue = funcToCustomize.call(this, ...args); 
// Or simply funcToCustomize(...args) if you prefer

// Some instructions if call terminates :
console.log('success, no error encountered during call');
return returnValue;
}
}

我已经在Firefox控制台中测试过了:

let original = function (x,y) {
console.log(x+y);
};
let custom = customizeFunction(original);
custom(2,3);
/* Output :
Calling original  
5  
success, no error encountered during call debugger eval code:12:17  
undefined
*/

它按预期工作。但无论何时:

console.log(custom);

它输出function customizeFunction(args)(而original输出function original(x,y)(。是否有一些属性可以更改为输出function original(x,y)function custom_original(x,y)

此外,original.length是2,而custom.length是0。我也可以更改这个吗?

尝试覆盖返回函数的toString方法

function customizeFunction(funcToCustomize) {
let customFunc = function(...args) {
// Some instructions, for example :
console.log('Calling', funcToCustomize.name);
// The function itself
let returnValue = funcToCustomize.call(this, ...args); 
// Or simply funcToCustomize(...args) if you prefer

// Some instructions if call terminates :
console.log('success, no error encountered during call');
return returnValue;
}
customFunc.toString = function () {
return funcToCustomize.toString();
}
return customFunc;
}

最新更新