注解/Annotation
你一定好奇@Component和@View到底是怎么回事。看起来像其他语言(比如python) 的装饰器,是这样吗?
ES6规范里没有装饰器。这其实利用了traceur的一个实验特性:注解。给一个类 加注解,等同于设置这个类的annotations属性:
1 //注解写法
2 @Component({selector:"ez-app"})
3 class EzApp{...}
与下面的写法产生的效果相同
1 class EzApp{...}
2 EzApp.annotations = [new Component({selector:"ez-app"})];
很显然,注解可以看做编译器(traceur)层面的语法糖,但和python的装饰器不同, 注解在编译时仅仅被放在annotation里,编译器并不进行解释展开 - 这个解释的工作是 Angular2完成的:

据称,注解的功能就是Angular2团队向traceur团队提出的,这不是traceur的默认选项, 因此你看到,配置systemjs在使用traceur模块时打开注解:
1 System.config({
2 map:{traceur:"lib/traceur"},
3 traceurOptions: {annotations: true}
4 });
例如:
1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>hello,angular2</title>
6 <!--模块加载器-->
7 <script type="text/javascript" src="lib/[email protected]"></script>
8 <!--Angular2模块库-->
9 <script type="text/javascript" src="lib/angular2.dev.js"></script>
10 <script>
11 //设置模块加载规则
12 System.baseURL = document.baseURI;
13 System.config({
14 map:{traceur:"lib/traceur"},
15 traceurOptions: {annotations: true}
16 });
17 </script>
18 </head>
19 <body>
20 <!--组件渲染锚点-->
21 <ez-app></ez-app>
22
23 <!--定义一个ES6脚本元素-->
24 <script type="module">
25 //从模块库引入三个类型定义
26 import {Component,View,bootstrap} from "angular2/angular2";
27
28 //组件定义 (注解写法)
29 //@Component({selector:"ez-app"})
30 //@View({template:"<h1>Hello,Annotation</h1>"})
31 //class EzApp{}
32
33 //组件定义 (非注解写法)
34 class EzApp{}
35 EzApp.annotations = [new Component({selector:"ez-app"}),
36 new View({template:"<h1>Hello,Annotation</h1>"})];
37
38 //渲染组件
39 bootstrap(EzApp);
40 </script>
41 </body>
42 </html>