-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.html
42 lines (37 loc) · 1.02 KB
/
observer.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 创建对象
var targetObj = {
age: 1
}
// 定义值改变时的处理函数
function observer(oldVal, newVal) {
// 其他处理逻辑...
console.info('name属性的值从 ' + oldVal + ' 改变为 ' + newVal);
}
// 定义name属性及其set和get方法
Object.defineProperty(targetObj, 'name', {
enumerable: true,
configurable: true,
get: function () {
return name;
},
set: function (val) {
//调用处理函数
observer(name, val)
name = val;
}
});
targetObj.name = 'Martin';
targetObj.name = 'Lucas';
console.info('targetObj:', targetObj)
</script>
</body>
</html>