Search code examples
javascripttypescriptecmascript-6interpreterecma

How to allow '@' keyword in Javascript


I'm trying to allow '@' functions in my application, what should I add or insert to allow JS to interpret it, just like "angular2 @Component".


Solution

  • The @ is used as a decorator in a new proposed feature for JavaScript. To use it you need to use a preprocessor like Babel. It is also available in typescript and widely used in Angular2. Example:

    function myDecorator(value) {
       return function(target) {
          target.myProperty = value;
       }
    }
    
    @myDecorator('myValue')
    class MyClass { }
    

    Decorators will not work by default on Babel, you can find information on enabling them here.

    Edit: Whether you consider @myDecorator('myValue') as @ being part of the function name or not, I think we can all acknowledge that it would look this way to those new to the language.

    Related Links:

    https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841 https://cabbageapps.com/fell-love-js-decorators/