1
+ // // 构建一个新的对象类型Object的构造器,以达到proxy的效果,无需递归拦截
2
+ class MyProxy {
3
+ constructor ( obj ) {
4
+ let map = new Map ( ) ;
5
+ this . _map = map ;
6
+ this . init ( obj , map ) ;
7
+ // let proxy = this.createProxy(map, obj);
8
+ // return proxy;
9
+ }
10
+ init ( obj , map ) {
11
+ for ( let prop in obj ) {
12
+ // console.log(prop)
13
+ this . def ( obj , '_obj_' , this ) ;
14
+ // if (typeof obj[prop] === 'object') {
15
+ // map.set(prop, Object.assign({}, obj[prop]));
16
+ // this.init(obj[prop], map);
17
+ // } else {
18
+ // map.set(prop, obj[prop]);
19
+ // }
20
+ }
21
+ }
22
+ def ( obj , key , val , enumerable ) {
23
+ Object . defineProperty ( obj , key , {
24
+ value : val ,
25
+ enumerable : ! ! enumerable ,
26
+ writable : true ,
27
+ configurable : true
28
+ } ) ;
29
+ }
30
+ createProxy ( map , obj ) {
31
+ for ( let prop in obj ) {
32
+
33
+ // if (typeof obj[prop] === 'object') {
34
+ // obj[prop] = this.createProxy(map,obj[prop]);
35
+ // // console.log(map.get(prop));
36
+ // }
37
+ Object . defineProperty ( obj , prop , {
38
+ get ( ) {
39
+ console . log ( `obj${ obj . toString ( ) } /prop:${ prop } => ${ map . get ( prop ) } ` )
40
+ return map . get ( prop ) ;
41
+ }
42
+ } ) ;
43
+ }
44
+ return obj ;
45
+ }
46
+ }
47
+ let temp = new MyProxy ( {
48
+ a : {
49
+ b : {
50
+ c : 1
51
+ }
52
+ }
53
+ } ) ;
54
+ // let obj = {
55
+ // 'a': {
56
+ // 'b': {
57
+ // 'c' : 1
58
+ // }
59
+ // }
60
+ // };
61
+ // function observe(obj) {
62
+ // if (obj !== null && typeof obj === 'object') {
63
+ // Object.keys(obj).forEach(key => {
64
+ // let internalValue = obj[key];
65
+ // observe(internalValue); // 递归调用observe,处理内部对象
66
+ // Object.defineProperty(obj, key, {
67
+ // get() {
68
+ // console.log(`Getting property: ${key}`);
69
+ // return internalValue;
70
+ // },
71
+ // set(newValue) {
72
+ // console.log(`Setting property: ${key} with value: ${newValue}`);
73
+ // internalValue = newValue;
74
+ // }
75
+ // });
76
+ // });
77
+ // }
78
+ // return obj;
79
+ // }
80
+
81
+ // obj = observe(obj);
82
+
83
+ // // console.log(obj.a.b); // 输出: Getting property: a, Getting property: b,然后输出: 1
84
+ // // obj.a.b = 2; // 输出: Setting property: b with value: 2
85
+ // console.log(obj.a.b.c); // 输出: Getting property: a, Getting property: b,然后输出: 2
86
+
87
+ // function def(obj, key, val, enumerable) {
88
+ // Object.defineProperty(obj, key, {
89
+ // value: val,
90
+ // enumerable: !!enumerable,
91
+ // writable: true,
92
+ // configurable: true
93
+ // });
94
+ // }
95
+ // def(obj,'_obj_',"a");
96
+ // console.log(obj)
0 commit comments