Friday, 12 May 2017

What is the `target` in javascript decorators

I'm playing with javascript decorators but I'm having a hard time with the target which is passed to the decorator function

For example, if you have

@Bar()
class Foo {
    @deprecated(true)
    doMagic() {}
}

function Bar() {
    return function decorator(target) {

    }
}

function deprecated(state) {
    return function decorator(target, name, config) {
         return config;
    }
}

I would expect that both targets are one and the same thing, right, well it isn't. For example

function Bar() {
    return function decorator(target) {
        let bar = new target(); // WORKS
        bar instanceof target; // -> true
    }
}

function deprecated(state) {
    return function decorator(target, name, config) {
         let bar = new target(); // ERROR
         let bar = new target.constructor() // WORKS

         bar instanceof target; // ‌TypeError: Right-hand side of 'instanceof' is not callable
         bar instanceof target.constructor // WORKS
         return config;
    }
}

As you can see there is a difference between both targets, and my question is what is wrong with that second target

I use node v7.8.0 and I'm using the follow babel plugins (.babelrc)

{
    "presets": [
        "es2015",
       "stage-0"
   ]

}



via Jeanluca Scaljeri

No comments:

Post a Comment