首页 > 解决方案 > 我应该使用原型装饰器还是有其他方法?

问题描述

例如,我有一些代码。我需要将日志记录功能添加到“测试”类的“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);

标签: javascript

解决方案


您可以将函数包装在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为正确的值。


推荐阅读