【问题标题】:Can a class decorator receive both the constructor function and additional arguments?类装饰器可以同时接收构造函数和附加参数吗?
【发布时间】:2016-04-11 14:15:10
【问题描述】:

我一直在玩 Babel 和装饰器。例如:

function test(target) { 
}

@test
class A {}

我担心的是,是否有某种方法可以对类使用装饰器,并且还能够为所谓的装饰器提供参数,并且不会失去将构造函数作为第一个参数的机会:

function test(target, arg1, argN) {
   // target will be "hello", arg1 will be "world" and argN undefined,
   // while I would expect target to be the constructor function
}

@test("hello", "world")
class A {}

【问题讨论】:

  • 你为什么不试试看它是如何工作的?
  • @torazaburo 你为什么不仔细阅读我的问题? :D 请参阅 test 函数内的注释。你不认为我已经尝试过自己了吗?
  • 您好,我不知道您具体尝试了什么,但如果您通过 babel-node 或类似方式运行程序,您将收到错误消息“未定义不是函数”或相等的。从中可以推断,在必要时查看转译的代码,问题是@test("hello", "world') 是未定义的,因为你没有从test 返回任何东西,而它应该评估为一个函数被装饰的对象将被传递。
  • @torazaburo 错了,它按照我在我的问题正文中描述的那样工作......也许你正在描述一个实际的 ES2015 在我的情况下会抛出什么,但如果我没记错的话,整个示例的行为与我在问题中描述的一样...

标签: javascript class decorator ecmascript-next


【解决方案1】:

它是这样工作的

function test(target, arg1, argN) {
  return function(clazz) {
     console.log(target, arg1, clazz)
  } 
}

@test("hello", "world")
class A {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2017-09-14
    • 2020-05-20
    • 1970-01-01
    • 2017-04-09
    • 2017-05-04
    • 2017-10-21
    相关资源
    最近更新 更多