Skip to content

Commit f71b970

Browse files
committed
More proxy handlers
1 parent 540d9e6 commit f71b970

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

JavaScript/4-has.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict';
2+
3+
const data = { name: 'Marcus Aurelius', city: 'Rome', born: 121 };
4+
5+
const person = new Proxy(data, {
6+
has(obj, key) {
7+
console.log('check', key);
8+
return (key in obj || key === 'age');
9+
},
10+
get(obj, key) {
11+
console.log('get', key);
12+
if (key === 'age') {
13+
return (
14+
new Date().getFullYear() -
15+
new Date(obj.born + '').getFullYear()
16+
);
17+
}
18+
return obj[key];
19+
}
20+
});
21+
22+
console.log('Try \'age\' in person');
23+
if ('age' in person) {
24+
console.log('Try person.age');
25+
if (person.age) {
26+
console.log('Try person[\'age\']');
27+
if (person['age']) {
28+
console.log({
29+
born: person.born,
30+
age: person.age
31+
});
32+
}
33+
}
34+
}

JavaScript/5-delete.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
'use strict';
2+
3+
const data = { name: 'Marcus Aurelius', city: 'Rome', born: 121 };
4+
5+
const person = new Proxy(data, {
6+
deleteProperty(obj, key) {
7+
console.log('delete', key);
8+
return true;
9+
}
10+
});
11+
12+
console.log(person);
13+
delete person.name;
14+
console.log(person);

0 commit comments

Comments
 (0)