-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDecorator.js
49 lines (42 loc) · 1.15 KB
/
Decorator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
function decorateSword(target, key, descriptor) {
// 首先获取到 init 方法
const initMethod = descriptor.value
// 宝剑添加攻击力 100 点
let moreAtk = 100
let returnObj
descriptor.value = (...args) => {
args[0] += moreAtk
returnObj = initMethod.apply(target, args)
return returnObj
}
}
function decorateArmour(target, key, descriptor) {
// 首先获取到 init 方法
const initMethod = descriptor.value
// 护甲添加防御力 100 点
let moreDef = 100
let returnObj
descriptor.value = (...args) => {
args[1] += moreDef
returnObj = initMethod.apply(target, args)
return returnObj
}
}
class Warrior {
constructor(atk=50, def=50, hp=100, mp=100) {
this.init(atk,def,hp,mp)
}
@decorateSword
@decorateArmour
init(atk, def, hp, mp) {
this.atk = atk
this.def = def
this.hp = hp
this.mp = mp
}
toString() {
return `攻击力:${this.atk}, 防御力: ${this.def}, 血量: ${this.hp}, 法力值: ${this.mp}`
}
}
const Reaper = new Warrior()
console.log(`勇者状态 => ${Reaper}`)