Toc
  1. The difference between Annotations and Decorators
    1. Annotations
    2. Conclusion
Toc
0 results found
catzillaorz
装饰器和注解The difference between Annotations and Decorators
2021/09/02 TS Decorators
The difference between Annotations and Decorators
  • Pbulished 03 May 2015
Annotations
  • Let’s start off with annotations. As mentioned, the Angular team announced AtScript as their language extension to JavaScript. AtScript comes with features like Type Annotations, Field Annotations and MetaData Annotations. We’re going to focus on metadata annotations. Let’s take a look at the following Angular component to get an idea of what metadata annotations can look like:
@Component({
selector: 'tabs',
template: `

  • Tab 1

  • Tab 2


`
})
export class Tabs {

}
  • We have a class Tabs that is basically empty. The class has one annotation @Component. If we’d remove all annotations, what would be left is just an empty class that doesn’t have any special meaning right? So it seems that @Component add some metadata to the class in order to give it a specific meaning. This is what annotations are all about. They are a declarative way to add metadata to code.

  • @Component is an annotation that tells Angular, that the class, which the annotation is attached to, is a component.

  • Okay, even if that seems to be quite clear, there are a few questions coming up:

  • Where do those annotations come from? This is nothing that JavaScript gives us out of the box right?

  • Who defined this annotations called @Component?

  • If this is part of AtScript, what does that translate to, so we can use it in today’s browsers?

  • Let’s answer these one by one. Where do those annotations come from? To answer that question, we need to complete the code sample. @Component is something we need to import from the Angular framework like this:

import {
ComponentMetadata as Component,
} from '@angular/core';
  • This pretty much answers our first question. Both annotations are provided by the framework. Let’s take a look at what the implementation of those annotations look like:
export class ComponentMetadata extends DirectiveMetadata {

constructor() {
...
}
}

……

read more

Conclusion
  • “AtScript Annotations” and decorators are nearly the same thing. From a consumer perspective we have exactly the same syntax. The only thing that differs is that we don’t have control over how AtScript annotations are added as metadata to our code. Whereas decorators are rather an interface to build something that ends up as annotation. Over a long term, however, we can just focus on decorators, since those are a real proposed standard. AtScript is deprecated, and TypeScript implements decorators.

  • I hope this article made some things clear though.

打赏
支付宝
微信
本文作者:catzillaorz
版权声明:本文首发于catzillaorz的博客,转载请注明出处!