-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.js
93 lines (68 loc) · 1.66 KB
/
proxy.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
86
87
88
89
90
91
92
93
//proxy without traps
let target = {};
let proxy = new Proxy(target, {});
proxy.test = 5;
console.log(target.test);
console.log(proxy.test); // 5
//proxy with traps (get)
let dictionary = {
'Hello': 'Hola',
'Bye': 'Adiós'
};
dictionary = new Proxy(dictionary, {
get(target, phrase) {
if (phrase in target) {
return target[phrase];
} else {
return phrase;
}
}
});
console.log(dictionary) // proxy type
console.log(dictionary['Hello'] ); // Hola
console.log(dictionary['Welcome to Proxy']); // Welcome to Proxy (translation is absent)
//proxy with traps (set)
let numbers = [];
numbers = new Proxy(numbers, {
set(target, prop, val) {
if (typeof val == 'number') {
target[prop] = val;
return true;
} else {
return false;
}
}
});
numbers.push(1);
numbers.push(2);
console.log(numbers.length); // 2
// numbers.push("test"); // TypeError (trap set on proxy returned false)
let user = {
name: "John"
};
function wrap(target) {
return new Proxy(target, {
get(proxyTarget, property, receiver) {
console.log(receiver)
if (property in proxyTarget) {
return Reflect.get(proxyTarget, property, receiver);
} else {
throw new Error('Error, this property is absent');
}
}
});
}
user = wrap(user);
console.log(user.name); // John
// console.log(user.age); // Error, this property is absent
let array = [1, 2, 3];
array = new Proxy(array, {
get(target, prop, receiver) {
if (prop < 0) {
prop = target.length + Number(prop);
}
return Reflect.get(target, prop, receiver);
}
});
console.log(array[-1]); // 3
console.log(array[-2]); // 2