typescript 注释和装饰器有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37317705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between annotation and decorator?
提问by Sarvesh Yadav
I am confused when to use term annotation and when to use decorator ?
我很困惑何时使用术语注释以及何时使用装饰器?
@Component({
selector: 'tabs',
template: `
`
})
export class Tabs {
}
回答by Thierry Templier
A decorator corresponds to a function that is called on the class whereas annotations are "only" metadata set on the class using the Reflect Metadata library.
装饰器对应于在类上调用的函数,而注释是使用 Reflect 元数据库在类上设置的“唯一”元数据。
With TypeScript and ES7, @Something
is a decorator. In the context of Angular2, decorators like @Component
, @Injectable
, ... define metadata for the decorated element using the Reflect.defineMetadata
method.
与 TypeScript 和 ES7 一起,@Something
是一个装饰器。在 Angular2 的上下文中,诸如@Component
, @Injectable
, ... 之类的装饰器使用Reflect.defineMetadata
方法为装饰元素定义元数据。
This question could interest you to find out what a decorator actually is:
这个问题可能会让你感兴趣,找出装饰器实际上是什么:
回答by Ayman Ali
In Angular, annotations are used for creating an annotation array. They are only metadata set of the class using the Reflect Metadata library.
在 Angular 中,注解用于创建注解数组。它们只是使用 Reflect Metadata 库的类的元数据集。
Decorators in Angular are design patterns used for separating decoration or modification of some class without changing the original source code.
Angular 中的装饰器是一种设计模式,用于在不更改原始源代码的情况下分离某个类的装饰或修改。
回答by Pardeep Jain
Traceur gives us annotations
. TypeScript gives us decorators
. But Angular 2 supports both.
Traceur 给了我们annotations
。TypeScript 为我们提供了decorators
. 但是 Angular 2 两者都支持。
Annotations create an "annotations" array. whereas Decorators are functions that receive the decorated object and can make any changes to it they like.
注释创建一个“注释”数组。而装饰器是接收装饰对象并可以对其进行任何他们喜欢的更改的函数。
As angular use TypeScript instead of atScript so it is using decorators. There are basically four kind of decorators are there which are
由于 angular 使用 TypeScript 而不是 atScript,所以它使用装饰器。基本上有四种装饰器,它们是
- Class decorators, e.g. @Component and @NgModule
- Property decorators for properties inside classes, e.g. @Input and @Output
- Method decorators for methods inside classes, e.g. @HostListener
- Parameter decorators for parameters inside class constructors, e.g. @Inject
- 类装饰器,例如@Component 和@NgModule
- 类内部属性的属性装饰器,例如@Input 和@Output
- 类内部方法的方法装饰器,例如@HostListener
- 类构造函数内部参数的参数装饰器,例如@Inject
For more in depth you can refer
更深入的可以参考