forked from sgaurav/understanding-es6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.js
37 lines (29 loc) · 956 Bytes
/
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
/**
* Proxies are special objects that allow you to provide custom implementations for operations on objects.
(e.g. property lookup, assignment, enumeration, function invocation, etc).
Proxies have a handler(a method that – if present – performs that operation),
and target(the operation is performed on target if the handler doesn't intercept it).
*/
let target = {
guest: "Welcome, Guest"
};
let proxy = new Proxy(target, {
get (obj, prop, val) {
return val in obj ? obj[val] : 'Howdy, ${val}'
},
set (obj, prop, val){
if(prop === 'password'){
if(val.length<8){
throw new TypeError('The length of password should be greater than 8');
} else {
obj[prop] = val;
}
} else {
obj[prop] = val;
}
}
});
proxy.guest; // "Welcome, Guest"
proxy.userX; // "Howdy, UserX"
proxy.password = 'abc'; //Error The length of password should be greater than 8.
proxy.age = 22; //age=22