Search code examples
javascriptclassdecoratorecmascript-next

Can a class decorator receive both the constructor function and additional arguments?


I've been playing with Babel and decorators. For example:

function test(target) { 
}

@test
class A {}

My concern is if there's some way to use a decorator against a class and also be able to give arguments to the so-called decorator and don't lose the chance to get the constructor function as first argument:

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

Solution

  • It works this way

    function test(target, arg1, argN) {
      return function(clazz) {
         console.log(target, arg1, clazz)
      } 
    }
    
    @test("hello", "world")
    class A {}