#TIL : Define property of an object in hacking way

Sometimes, we want to define a property of an advanced object (has setter and getter function).

Now, we could use this helper function Object.defineProperty to define property of an object in a cool way.

Example :

1
2
3
4
5
6
7
8
9
10
const foo = {};

Object.defineProperty(a, 'bar', {
value: 'hogehoge',
writable: false,
});

console.log(foo.bar); // 'hogehoge'
foo.bar = 'foo bar'; // throw an error in strict mode
console.log(foo.bar); // still be 'hogehoge'

Modifying setter, getter function

1
2
3
4
5
6
7
8
9
10
11
// Get callstack which function is getting or setting cookie value
Object.defineProperty(document, 'cookie', {
get: function() {
console.log('get !');
console.trace();
},
set: function(val) {
console.log('set = ', val);
console.trace();
},
});

Comments