Javascript - Object Accessor (getter / setter)

About

Object - (Accessors|Get|Getter) Methods in javascript of property

Since ECMAScript 5.

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

Ref

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





Discover More
Javascript - (Object) Property

Property Management of an object A property has : a key and a value Property names can be Reference/Operators/Object_initializerdynamic Reference/Operators/delete A property may be...



Share this page:
Follow us:
Task Runner