命名空间
以namespace关键值定义命名空间.
namespace Obj{
export interface Person{
name:string;
age:number;
getMsg(name:string):string{}
}
}
new Obj.Serson()
装饰器
装饰器是一种特殊类型的声明,它可以用在类声明、方法、属性或者参数上。顾名思义,它是用来给附着的主体进行装饰,添加额外的行为。
装饰器使用@expression这种形式,expression求值后必须为一个函数,它会在运行时被调用,被装饰的声明信息做为参数传入。
类装饰器
类装饰器:类装饰器在类声明之前被声明(紧靠着类声明)。类装饰器应用于类构造函数,可以用来监视,修改或替换类定义。 传入一个参数
function run(target: any) {
return class extends target {
type: string = 'Web开发工程师'
getType() {
console.log(this.type)
}
}
}
@run
class Person {
type: string | undefined;
constructor(type: string = "工程师") {
this.type = type;
}
getType() {
console.log(this.type)
}
}
new Person().getType()
属性装饰器
属性装饰器接收两个参数(原型对象,参数)
属性装饰器表达式会在运行时当作函数被调用,传入下列2个参数:
1、对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
2、成员的名字。
function test(params: any) {
return function (target: any, attr: any) {
debugger
target[attr] = params;
}
}
class Person {
@test('工人')
type: string | undefined;
constructor(type: string = "工程师") {
}
getType() {
console.log(this.type)
}
}
new Person().getType()
方法装饰器
它会被应用到方法的属性描述符上,可以用来监视,修改或者替换方法定义。
方法装饰会在运行时传入下列3个参数:
1、对于静态成员来说是类的构造函数,对于实例成员类的原型对象。
2、成员的名字。
3、成员的属性描述符。
function test(parems?: any): Function {
return function (target: any, name: string, desc: any) {
let fn: Function = desc.value;
desc.value = (...arr: Array<any>): void => {
arr = arr.map(v => String(v));
fn(arr);
};
};
}
class Person {
type: string | undefined;
constructor(type: string = "工程师") {
}
@test()
getType( ...arr: Array<any>) {
console.log(arr)
}
}
new Person().getType(1,"2",3)
方法参数装饰器
参数装饰器表达式会在运行时当作函数被调用,可以使用参数装饰器为类的原型增加一些元素数据, 传入下列3个参数:
1、对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
2、方法的名字。
3、参数在函数参数列表中的索引。
评论 (0)