【问题标题】:Lodash or Javascript decorator for all functions in object对象中所有函数的 Lodash 或 Javascript 装饰器
【发布时间】:2020-01-28 21:56:33
【问题描述】:

对于下面的对象

const ourObject = {
    func1: (arg1, arg2, arg3) => arg3
    func2: (arg1) => void
};

ourFunction(ourObject);

ourObject.func1(1,2,3);

在上面之后我想记录参数并返回 func1 的输出,所以我认为需要遍历所有字段,然后使用类似下面的东西

console.log(argmuments)
return func.apply(arguments)

lodash 已经有解决方案了吗?

【问题讨论】:

  • 我不知道你在问什么。所以你想基本上覆盖对象中的所有方法并记录参数?
  • 您在寻找Proxy吗?

标签: javascript typescript lodash


【解决方案1】:

所以循环遍历键、制作副本、定义新方法、引用参数并调用原始方法。

const ourObject = {
  func1: (arg1, arg2, arg3) => arg3,
  func2: (arg1) => 'bar'
}

// Loop over the keys of the object
Object.keys(ourObject).forEach((key) => {
  // copy the original method
  const org = ourObject[key]
  // create the new method
  ourObject[key] = function(...args) {
    // log the arguments
    console.log(key, args)
    // call the original
    return org.apply(this, args)
  }
})

console.log(ourObject.func1(1, 2, 3))
console.log(ourObject.func2('foo'))

【讨论】:

  • 猜测如何遍历字段是错误的?
  • 不知道为什么会被否决。我正在回答这个问题,并且几乎有相同的策略。
  • 没有 Lodash?不过,只是猜测。老实说,OP 的问题不是很清楚,这可能是解决方案,但我不太确定。
  • 因为我已经用我的代码换成了 ES6/7,所以我放弃了 lodah/jQuery。我使用它的东西不在核心中,所以为什么要添加额外的包袱。有人可以用_.keys和forEach添加答案,但基本上是一样的。
猜你喜欢
  • 1970-01-01
  • 2019-06-16
  • 2017-06-19
  • 2011-06-28
  • 2018-11-12
  • 2014-02-20
  • 2021-10-08
  • 1970-01-01
  • 2020-12-18
相关资源
最近更新 更多