decorator是 一个函数,用来修改类的行为,在代码编译时产生作用
一、类修饰
一个参数
第一个参数是target,指向类本身
function testable(target) {
target.isTestable = true
}
@testable
class Example {}
Example.isTestable ; //true
多个参数 --嵌套实现
function testable(isTestable) {
return function(target) {
target.isTestable=isTestable
}
}
@testable(true)
class Example()
Example.isTestable //true
二、方法修饰
3个参数:target (类的原型对象)、name(修饰的属性名)、descriptor(该属性的描述对象)
class Example {
@writeable
sum(a,b) {
return a + b;
}
}
function writeable(target, name, descriptor) {
descriptor.writeable = false;
return descriptor //必须返回
}
修饰器执行顺序,由内向外执行
class Example {
@logMethod(1)
@logMethod(2)
sum(a,b) {
return a + b ;
}
}
function logMethod(id) {
console.log('evaluated logMethod'+id);
return (target, name, desctiptor) => console.log('excute logMethod+${id}')
}
// evaluated logMethod 1
//evaluated logMethod 2
//excuted log Method 2
//excuted log Method 1
实际应用:
1、防抖动(采用ts模版)
(1) 定时器
let handle : any
export const Debounce = (cb?:Function) => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const fn = descriptor.value
descriptor.value = function () {
cb && cb(this)
clearTimeout(handle)
handle = setTimeout(() => {
fn.call(this,...arguments)
},500)
}
}
}
(2)时间差
var enterTime = 0
export const Debounce = (cb?: Function) => {
return (target: any, propertyKey: string, descriptor:PropertyDescriptor) => {
const fn = descriptor.value
descriptor.value = function () {
cb && cb(this)
var gapTime = 500
var backTime: any = new Date()
if(backTime - enterTime > gapTime) {
fn.call(this,...arguments)
enterTime = backTime
}
}
}
}
2、登陆拦截
如果没登陆的话同意跳转到登陆页面,否则就执行自己的函数
export const UnLogin = (cb?: Function) => {
return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
const fn = descriptor.value
descriptor.value = function() {
cb && cb(this)
if(!Utils.isLogin) {
//没有登陆
Taro.navigateTo({url: '/packages/login/auth/userinfo/index'})
return
}
fn.call(this,...arguments)
}
}
}
总结:以上定义了两种装饰器:类装饰器和方法修饰器,以及他们的一些应用~