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)
}
}
}
總結:以上定義了兩種裝飾器:類裝飾器和方法修飾器,以及他們的一些應用~