-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
89 lines (82 loc) · 2.17 KB
/
proxy.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/***
* 代理模式
* 代理模式把代理对象插入到访问者和目标对象之间,
* 从而为访问者对目标对象的访问引入一定的间接性。
* 正是这种间接性,给了代理对象很多操作空间,
* 比如在调用目标对象前和调用后进行一些预操作和后操作,
* 从而实现新的功能或者扩展目标的功能。
*/
//ES6 使用proxy
const SuperStar = {
name: "小鲜肉",
hasTime: false,
playAdvertisement(ad) {
console.log(`I am ${this.name},I say ${ad}`);
},
};
const ProxyAssistant = {
name: "经纪人",
scheduleTime(ad) {
let proxy = new Proxy(SuperStar, {
set(obj, prop, val) {
if (prop !== "hasTime") return;
if (val) {
obj.hasTime = true;
obj.playAdvertisement(ad);
}
},
});
setTimeout(() => {
console.log("小鲜鲜有空了");
proxy.hasTime = true;
}, 2000);
},
playAdvertisement(reward, ad) {
if (reward > 10000) {
console.log("安排上~");
this.scheduleTime(ad);
} else {
console.log("没有档期~");
}
},
};
ProxyAssistant.playAdvertisement(100, "蒙牛好味道");
ProxyAssistant.playAdvertisement(100000, "旺仔真好喝");
//ES5 使用 Object.defineProperty
const SuperStar = {
name: "小鲜肉",
hasTime: false,
playAdvertisement(ad) {
console.log(`I am ${this.name},I say ${ad}`);
},
};
const ProxyAssistant = {
name: "经纪人",
scheduleTime(ad) {
Object.defineProperty(SuperStar, "hasSechedule", {
get() {
return SuperStar.hasSechedule;
},
set(val) {
if (val === true && SuperStar.hasTime === false) {
SuperStar.hasTime = true;
SuperStar.playAdvertisement(ad);
}
},
});
setTimeout(() => {
console.log("小鲜鲜有空了");
SuperStar.hasSechedule = true;
}, 2000);
},
playAdvertisement(reward, ad) {
if (reward > 10000) {
console.log("安排上~");
this.scheduleTime(ad);
} else {
console.log("没有档期~");
}
},
};
ProxyAssistant.playAdvertisement(100, "蒙牛好味道~");
ProxyAssistant.playAdvertisement(100000, "旺仔真好喝~");