javascript - 我应该使用原型装饰器还是有其他方法?
问题描述
例如,我有一些代码。我需要将日志记录功能添加到“测试”类的“fn”功能中。同时它应该像原始函数一样工作而不做任何更改(接受并返回相同的值),但另外在控制台中显示“调用”。我无法更改原始的“测试”类函数或创建的对象。代码只能写在指定区域。结果,当我在“代码结束”之后调用 console.log 时,我应该同时看到结果和指定的“调用”。有可能吗?你能帮忙或建议我怎么做吗?
class Test {
constructor(num) {
this.num = num;
}
fn(...numbers) {
const sum = (a, b) => a + b;
return this.num + numbers.reduce(sum);
}
}
// Сode here
// End of code
const mytest = new Test(5);
const result = mytest.fn(2, 3, 4);
console.log('Result: ', result);
解决方案
您可以将函数包装在Test.prototype
:
const original = Test.prototype.fn;
Test.prototype.fn = function(...args) {
console.log("Log the call here");
return original.apply(this, args);
};
现场示例:
class Test {
constructor(num) {
this.num = num;
}
fn(...numbers) {
const sum = (a, b) => a + b;
return this.num + numbers.reduce(sum);
}
}
// Сode here
const original = Test.prototype.fn;
Test.prototype.fn = function(...args) {
console.log("Log the call here");
return original.apply(this, args);
};
// End of code
const mytest = new Test(5);
const result = mytest.fn(2, 3, 4);
console.log('Result: ', result);
请注意我调用原始文件的方式,apply
以便设置this
为正确的值。
推荐阅读
- javascript - API JIVE 搜索问题和讨论
- db2 - DB2 将两个 longvarchar 列连接成新的 CLOB 列
- algorithm - 枢轴时快速排序的时间复杂度(将列表拆分为 90%:10%)(对于均匀深度,总是最小元素)
- documentation - 如何在文档中并排显示代码和伪代码?
- ruby-on-rails - 使用活动存储映像获取 MD5 哈希
- javascript - 闭包编译器:它如何决定何时内联?
- python - 试图将有序字典写入 csv,但结果为空白
- hash - 如何检查两个散列字符串是否属于相同的明文密码
- mongodb - Mongo - 在 $project 之后排序不起作用
- r - 在ggplot中使用位置=“填充”时出错