typescript装饰器
dearweb
发布:2021-08-01 11:27:54阅读:
常见的装饰器有:类装饰器、属性装饰器、方法装饰器、参数装饰器。装饰器的写法:普通装饰器(无法传参),装饰器工厂(可传参)。装饰器是过去几年中js最大的成就之一,已是es7的标准之一。
普通装饰器
//装饰器
// function logClass(params:any){
// console.log(params)
// params.prototype.apiUrl = '动态扩展属性'
// params.prototype.apiRun = function(){
// console.log('我在跑步')
// }
// }
// @logClass
// class HttpClient {
// constructor() {
// }
// getData(){
// }
// }
// let http = new HttpClient()
// console.log(http) // [Prototype]
// console.log(http.apiRun()) //我在跑步装饰器工厂(可传参)
// function logClass(params:string){
// return function(target:any){
// console.log(target,params) // ƒ HttpClient() {} "hello"
// target.prototype.hello = params
// }
// }
// @logClass('hello')
// class HttpClient {
// constructor() {
// }
// getData(){
// }
// }
// let http = new HttpClient()
// console.log(http.hello) // hello类装饰器
类装饰器下面是一个重载构造函数的例子,类装饰器表达式会在运动时当做函数被调用,类的构造函数作为其唯一的参数,如果类装饰器返回一个值,它会使用提供的构造函数来替换类的声明。
// function logClass(target:any){
// console.log(target) // ƒ HttpClient() {this.APIUrl = 'dearweb.cn';}
// return class extends target {
// APIUrl:any = 'wuhan.com'
// getData(){
// console.log(this.APIUrl)
// }
// }
// }
// @logClass
// class HttpClient {
// public APIUrl:string| undefined
// constructor() {
// this.APIUrl = 'dearweb.cn'
// }
// getData(){
// console.log(this.APIUrl)
// }
// }
// let http = new HttpClient()
// console.log(http) // APIUrl: "wuhan.com" [[Prototype]]: HttpClient constructor: ƒ class_1() getData: ƒ ()属性装饰器
属性装饰器表达式会在运行时当作函数被调用传入下列2个参数;
1.对于静态成员来说是类的构造函数,对于实例成员来说是类的原型对象
2.成员的名字
// 类装饰器
function logClass(params:any){
return function(target:any) {
// console.log(params,target);
}
}
// 属性装饰器
function logProperty(params:any){
return function(target:any,attr:any){
console.log(target,attr);
target[attr] = params
}
}
@logClass('www.dearweb.cn')
class HttpClient {
@logProperty('http://baidu.com')
public url:any| undefined
constructor() {
}
getData(){
console.log(this.url)
}
}
let http = new HttpClient()
http.getData()小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧