-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReflect.html
More file actions
41 lines (38 loc) · 1.02 KB
/
Reflect.html
File metadata and controls
41 lines (38 loc) · 1.02 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// 使用Proxy实现观察者模式
// 观察者模式(Observer mode)指的是函数自动观察数据对象,一旦对象有变化,函数就会自动执行。
const queuedObservers = new Set();
const observe = fn => queuedObservers.add(fn);
const observable = obj => new Proxy(obj, {set});
function set(target, key, value, receiver) {
const result = Reflect.set(target, key, value, receiver);
queuedObservers.forEach(observer => observer());
return result;
}
const person = observable({
name: '张三',
age: 20
});
function print() {
console.log(`${person.name}, ${person.age}`);
}
observe(print);
person.name = '李四';
person.age = 43;
function showF(a,b,callBack) {
var num = a+b;
callBack(num);
}
showF(1,2,function (num) {
console.log(num);
})
</script>
</body>
</html>