【问题标题】:What is the purpose of the "@" symbol in Javascript classes? [duplicate]Javascript 类中“@”符号的用途是什么? [复制]
【发布时间】:2021-10-09 15:21:07
【问题描述】:

在 AdonisJS 的 this example 中,Post 类定义包括 @column 部分。有人可以解释这是做什么的吗?我假设它在 Post 类中创建了多个“列”类的实例作为成员变量,每个实例都有不同的名称和数据类型。但这是如何工作的?@ 符号是干什么用的?

  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
  }

以下是否等效(没有定义的数据类型)?

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

更新:

在意识到 AdonisJS 是用 TypeScript 编写后,我找到了this,它回答了这个问题。

【问题讨论】:

标签: javascript class inheritance class-properties


【解决方案1】:

这些被称为“装饰器”,这是一个提议的 javascript 功能。

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

该提案已经经过多次迭代。 TypeScriptbabel 都有自己的装饰器实现。

装饰器可以修改整个类或类字段,例如通过调用 Object.defineProperty(classPrototype, key, {...})。

装饰器的具体作用取决于它的实现功能。

【讨论】:

    猜你喜欢
    • 2018-09-11
    • 2011-08-08
    • 2022-04-11
    • 1970-01-01
    • 2015-04-18
    • 2018-01-12
    • 2010-11-05
    • 2011-03-28
    相关资源
    最近更新 更多