跳到主要内容

Decorator

// 1. 用于class
// target表示类本身
function setClassProperty(target) {
target.n = 'akara'
}

@setClassProperty
class People {

}

console.log(People.n) // akara

// 2. 用于类方法
function log(target, key, descriptor) {
const fn = descriptor.value
descriptor.value = function (...args) {
console.log(`calling ${key} with args: ${args}`)
return fn.apply(this, args)
}
return descriptor
}

class People {
constructor(name, age) {
this.name = name
this.age = age
}

@log
getName() {
return this.name
}
}

const p = new People('akara', 20)
console.log(p.getName())

// 3. 用于实例属性
// 装饰实例属性的时候,descriptor有个属性为initializer
// 通过修改这个函数的返回值,实例化时的属性值也不同
function test(target, key, descriptor) {
const fn = descriptor.initializer
descriptor.initializer = function () {
const v = fn.apply(this)
const randomNumber = ~~(Math.random() * 1000)
return `${v}-${randomNumber}`
}
}

class People {
@test
name = 'akara'
}

const p = new People()
console.log(p.name)
// 执行顺序 1 3 4 2
function f() {
console.log(1);
return function (
target,
key,
descriptor,
) {
console.log(2);
};
}

function g() {
console.log(3);
return function (
target,
key,
descriptor,
) {
console.log(4);
};
}

class C {
@f()
@g()
method() {}
}

// @f @g test 相当于数学中的 f(g(test))