装饰器
function decorator(){}@decoratorclass Hd{}
这样子配置还是不行
tsc -w
是通过tsconfig.json文件进行配置的,我们没有这个文件,所以我们得
tsc --init
来创建一个tsconfig.json
在tsconfig.json中开启experimentalDecorators和emitDecoratorMetadata来开启这个新特性
之后的2.ts中报的错误会少点,就是缺少参数
function decorator(target:object){}@decoratorclass Hd{}
我们这个时候去tsc -w就不报错了
类装饰器
//坦克class Tank{//问题就是获取元素的坐标}//玩家class Player{}
碰到画布或者子弹游戏就结束,这样我们可以去定义一个装饰器;你要明白装饰器的定义就是一个函数
//ClassDecorator: 定义一个class的装饰器const moveDecorator: ClassDecorator
进入ClassDecorator里面能看到:
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
如果我们把装饰器放在
@moveDecoratorclass Tank{}
那target参数就是Tank;
如果我们把装饰器放在
@moveDecoratorclass Player{}
那target参数就是player
编译一下内容
const moveDecorator: ClassDecorator = (target:object)=>{console.log(target)}@moveDecoratorclass Tank{}
node 2.js
来运行,得到的结果
[class Tank]
const moveDecorator: ClassDecorator = (target:object)=>{console.log(target)//在原型对象上增加方法target.prototype.getPosition = ():{x:number,y:number} =>{return {x:100,y:200}}}class Tank{}const t = new Tank();console.log(t.getPosition())
错误先不管(ts报错,但是js还是会添加的)
运行js
node 2.js
得到的结果:
[class Tank]{ x: 100, y: 200 }
报的错是类上没有这个属性,所以可以
const moveDecorator: ClassDecorator = (target:Function)=>{console.log(target)//在原型对象上增加方法target.prototype.getPosition = ():{x:number,y:number} =>{return {x:100,y:200}}}@moveDecorator//坦克class Tank{public getPosition(){}}const t = new Tank();console.log(t.getPosition())
也可以:
const moveDecorator: ClassDecorator = (target:Function)=>{console.log(target)//在原型对象上增加方法target.prototype.getPosition = ():{x:number,y:number} =>{return {x:100,y:200}}}@moveDecoratorclass Tank{}const t = new Tank();// console.log((<any>t).getPosition())console.log((t as any).getPosition())
你也可以在原型对象上添加一个name的属性,装饰器和继承都是对原型对象进行操作。
装饰器decorator语法糖
const moveDecorator: ClassDecorator = (target:Function)=>{console.log(target)//在原型对象上增加方法target.prototype.getPosition = ():{x:number,y:number} =>{return {x:100,y:200}}}class Tank{}const t = new Tank()moveDecorator(Tank)
输出结构与
const moveDecorator: ClassDecorator = (target:Function)=>{...}@moveDecoratorclass Tank{}const t = new Tank()console.log((t as any).getPosition())
是一致的
装饰器的叠加
const moveDecorator: ClassDecorator = (target:Function)=>{console.log(target)//在原型对象上增加方法target.prototype.getPosition = ():{x:number,y:number} =>{return {x:100,y:200}}}const MusicDecoator:ClassDecorator = (target:Function) =>{target.prototype.playMusic = ():void =>{console.log('播放音乐')}}@moveDecorator@MusicDecoatorclass Player{}const p = new Player()console.log((p as any).playMusic())
产生的结果:
[class Player]播放音乐undefined
