You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 9ad229c
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: JavaScript/TypeScript/类型使用/Decorator.md
-147Lines changed: 0 additions & 147 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -156,150 +156,3 @@ p.test('Hello Jony');
156
156
- target: 类本身
157
157
- key:该参数所在的函数的函数名
158
158
- index: 该参数在函数参数列表中的索引值
159
-
160
-
# 注解与元数据操作
161
-
162
-
所谓注解的定义就是:为相应的类附加元数据支持。所谓元数据可以简单的解释,就是修饰数据的数据,比如一个人有 name,age 等数据属性,那么 name 和 age 这些字段就是为了修饰数据的数据,可以简单的称为元数据。通过注解添加元数据,然后在装饰器中获取这些元数据,完成对类、类的方法等等的修改,可以在装饰器中添加元数据的支持,比如可以可以在装饰器工厂函数以及装饰器函数中添加元数据支持等。
163
-
164
-
## 注解使用
165
-
166
-
Reflect Metadata 是 ES7 的一个提案,它主要用来在声明的时候添加和读取元数据。Reflect Metadata 的 API 可以用于类或者类的属性上,如:
这里的 format 可以作为装饰器函数的工厂函数,因为 format 函数返回的是一个装饰器函数,上述的方法定义了元数据 `Sysmbol("format")`,用 Sysmbol 的原因是为了防止元数据中的字段重复,而 format 定义了取元数据中相应字段的功能。接着我们来在类中使用相应的元数据:
256
-
257
-
```ts
258
-
classGreeter {
259
-
@format('Hello, %s')
260
-
name:string;
261
-
262
-
constructor(name:string) {
263
-
this.name=message;
264
-
}
265
-
sayHello() {
266
-
let formatString =getFormat(this, 'name');
267
-
returnformatString.replace('%s', this.name);
268
-
}
269
-
}
270
-
271
-
const g =newGreeter('Jony');
272
-
console.log(g.sayHello());
273
-
```
274
-
275
-
在上述中,我们在 name 属性的装饰器工厂函数,执行`@Format("Hello, %s")`,返回一个装饰器函数,且该装饰器函数修饰了 Greeter 类的 name 属性,将“name”属性的值写入为"Hello, %s"。然后再 sayHello 方法中,通过 getFormat(this,"name") 取到 formatString 为“Hello,%s”.
0 commit comments