About
Object - (Accessors|Get|Getter) Methods in javascript of property
Since ECMAScript 5.
Articles Related
Usage
- If your are in control of the object, you can audit if a property was accessed (otherwise you can audit with a proxy)
Management
new Object: Set / get
Example:
- Using the get operator (Standard-compliant ways). The property that save the value should not have the same name (otherwise you get a recursion)
var user = {
private_name: '',
get name() { console.log('name was accessed'); return this.private_name; },
set name(name) { console.log('name was set'); this.private_name = name; }
};
user.name = 'nico';
console.log(user.name);
Actual Object
defineProperty
const user = { private_name: '' };
Object.defineProperty(user, 'name', {
get: function() { console.log('name was accessed'); return this.private_name; },
set: function(name) { console.log('name was set'); this.private_name = name; }
});
user.name = 'nico';
console.log(user.name);
defineGetter
The __defineGetter__ (deprecated): Ref
- allows a getter to be defined on a pre-existing object.
- binds an object's property to a function to be called when that property is looked up.
Example:
- using __defineGetter__ (deprecated) to track the read of user agent
window.navigator.sniffed = false;
const userAgent = window.navigator.userAgent;
window.navigator.__defineGetter__('userAgent', function() {
window.navigator.sniffed = true;
return userAgent;
});
console.log("The userAgent property was read: "+window.navigator.sniffed);
console.log("The user Agent is "+window.navigator.userAgent);
console.log("The userAgent property was read: "+window.navigator.sniffed);
Remove
delete object.setter
delete object.getter