How to allow '@' keyword in Javascript

197 views Asked by At

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".

2

There are 2 answers

6
Philip Kirkbride On BEST ANSWER

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/

0
Michael Troger On

According to a variable name validator for JavaScript, @ is a:

invalid identifier according to ECMAScript 6 / Unicode 8.0.0

And so it is invalid for function names as well. See also: What characters are valid for JavaScript variable names? In Angular you actually use TypeScript and they make use of @ as a decorator of a function, but it's not used in a function name.