-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (63 loc) · 1.88 KB
/
index.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
let person = {
name: 'Kuba',
age: 33
};
// handler will set traps, handler use Reflect api
let handler = {
/* function has the same structure as Reflect.get() */
get: function (target, property) { return property in target ? target[property] + '!' : 0; },
set(target, property, value) {
if (value.length > 2) {
// target[property] = value;
// or
Reflect.set(target, property, value);
}
// nothing happen so you cant change
}
};
const proxy = new Proxy(person, handler);
console.log(proxy.age); // 33!
console.log(proxy.ages); // 0
//console.log(proxy.ages = 112); // no change: (112).length === undefined && !(undefined > 2)
console.log(proxy.ages = '112'); // ok
console.log((proxy.ages)); // 112!
/* Setting proxy as prototype */
let person2 = {
name: 'John',
age: '22'
};
Reflect.setPrototypeOf(person2, proxy);
console.log(person2.name); // John
console.log(person2.hobbies); // 0 - proxy works here
/* nested proxy */
const handler2 = {
// proxy code
};
/* It doesn't do anything right now, but just to show it's valid */
let nestedProxy = new Proxy(proxy, handler2);
// wrapping functions
const log = (message) => console.log(message);
let fnHandler = {
apply(target, thisArg, argumentsList) {
if (argumentsList.length === 1) {
return Reflect.apply(target, thisArg, argumentsList);
}
console.log('This function must have exactly one argument.');
}
};
const fnProxy = new Proxy(log, fnHandler);
fnProxy('Hello'); // Hello
fnProxy(); // This function must have exactly one argument.
/* Revocable proxy */
const rvcPerson= {
age: 22,
name: 'Anne'
};
const rvcHandler = {
get(target, property) { return Reflect.get(target, property); }
};
const { proxy: rvcProxy, revoke } = Proxy.revocable(rvcPerson, rvcHandler);
console.log(rvcProxy.name);
/* No more operations on this proxy */
revoke();
console.log(rvcProxy.name); // type error: cannot use proxy after revoke