-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlesson_5.js
More file actions
43 lines (34 loc) · 848 Bytes
/
lesson_5.js
File metadata and controls
43 lines (34 loc) · 848 Bytes
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
// JS Nuggets: Proxies!
// Syntax: var p = new Proxy(target, handler);
// Example 1
var handler = {
get (target, key) {
return key in target ? target[key] : 37;
}
};
var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b);
console.log('c' in p, p.c);
// Example 2
let validator = {
set: function(obj, prop, value) {
if (prop === "age") {
if (typeof value !== "number" || Number.isNaN(value)) {
console.log("Age must be a number")
}
if (value < 0) {
console.log("Age must be a positive number")
}
}
obj[prop] = value;
return true;
}
};
let person = new Proxy({}, validator);
person.age ='young';
console.log(person.age)
person.age = -30;
person.age = 100;
console.log(person.age)