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;
}