-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.html
95 lines (75 loc) · 2.04 KB
/
demo.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
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
90
91
92
93
94
95
<!DOCTYPE html>
<html>
<head>
<title>DefineProperty Demo</title>
</head>
<body>
<p class="text">text</p>
<input type="text" value="" class="textInput">
<script type="text/javascript">
var str = '';
var person = {
name: 'angeila',
age: 18
};
var textInput = document.getElementsByClassName('textInput')[0];
Object.defineProperty(person, 'age', {value: 24});
Object.defineProperty(person, 'location', {value: 'beijing'});
console.log(person)
// 可枚举的属性
Object.defineProperty(person, 'location1', {
value: 'beijing1',
enumerable: false
});
for(var key in person) {
console.log(person[key]);
}
console.dir(person);
// 通过Object.defineProperty可以自定义属性的getter和setter
Object.defineProperty(person, 'house', {
get: function() {
console.log('you get me.');
return str + ' get ';
},
set: function(newValue) {
str = newValue + ' set ';
console.log('you set me.')
}
});
person.house = 'yes';
console.log(person.house);
// 模拟双向绑定
Object.defineProperty(person, 'car', {
get: function() {
// console.log('you get me.');
// return str + ' get ';
},
set: function(newValue) {
// str = newValue + ' set ';
// console.log('you set me.')
document.getElementsByClassName('text')[0].innerHTML = newValue;
}
});
textInput.onchange = function() {
person.car = textInput.value;
};
// Object.defineProperty是ECS5方法,所以IE8以下无效。
// 所以得找一种兼容性方案:VBScript
// 不懂VBScript,没弄懂怎么实现的。。
// ES6的Proxy也有类似功能:监听对象身上发生了什么事,并做相应处理
// 被监听的对象
var coder = {
name: 'Angelia',
age: 18
};
var interceptor = {
set: function(receiver, property, value) {
console.log(proper, ' is changed to ', value);
receiver[property] = value;
}
};
coder = Proxy(coder, interceptor); // 由于浏览器基本没实现,所以这里会报错
coder.age = 24;
</script>
</body>
</html>