很多语言都有装饰器,比如java和python,装饰器的目的是扩展功能使用,它的本质是一个函数,简单地装饰器
#不带参装饰器
// 装饰器
function zsq(target:any){
// target 就是Student
target.prototype.name = '动态扩展的属性';
target.prototype.run = ()=>{
console.log('动态扩展的方法');
}
}
@zsq
class Student {
constructor(){
}
dothing(){
}
}
let stu:any = new Student();
console.log(stu.name);
stu.run()
#带参装饰器
//装饰器工厂
let zsq = (msg:string)=>{
return (target:any)=>{
target.prototype.name = msg
}
}
@zsq('我是装饰器工厂')
class Student {
constructor(){
}
dothing(){
}
}
let stu = new Student();
console.log(stu.name)
#属性装饰器
function defineProperty(parames:any){
return function(target:any,attr:any){
target[attr] = parames
}
}
class Student {
@defineProperty('http://www.baidu.com')
public url:any;
constructor(){
}
dothing(){
console.log(this.url)
}
}
let stu = new Student();
console.log(stu.dothing())