Search code examples
javascriptclassinheritanceclass-properties

What is the purpose of the "@" symbol in Javascript classes?


In this example on AdonisJS, the Post class definition includes @column sections. Can someone explain what this does? I assume it's creating multiple instances of the 'column' class within the Post class as member variables, each instance having a different name and data type. But how does this work and what is the @ symbol for?

  import { column, BaseModel } from '@ioc:Adonis/Lucid/Orm'

  export default class Post extends BaseModel {
    @column({ isPrimary: true })
    public id: number

    @column()
    public title: string

    @column()
    public description: string
  }

Would the following be equivalent (without the defined data types)?

export default class Post extends BaseModel
{
   constructor()
   {
      this.id = new column({ isPrimary: true });
      this.title = new column();
      this description = new column();
   }
}

UPDATE:

After realizing AdonisJS is written in TypeScript, I found this, which answers the question.


Solution

  • These are called "decorators", a proposed javascript feature.

    https://github.com/tc39/proposal-decorators

    The proposal has gone through several iterations already. TypeScript and babel both have their own implementations of decorators.

    Decorators can modify whole classes or class fields, e.g. by calling Object.defineProperty(classPrototype, key, {...}).

    What exactly the decorator does is dependent on it's implementing function.