darxtrix
darxtrix

Reputation: 2040

Javascript overriding the property setting functionality

JavaScript is dynamic. Cool !

I have the following constructor function :

function Preferences () {

  this._preferences = {}

}

var obj = new Preferences()

I want to achieve something like this:

>>> obj.something = 'value'
>>> this._preferences['something']
    'value'

That is setting the property of the obj does not actually set it's own property but that of obj._preferences. That is I want to override the default behavior.

Is it possible ?

EDIT : I want to achieve this for all property names i.e the name of the property to be set is not already known.

Upvotes: 0

Views: 363

Answers (2)

SharpEdge
SharpEdge

Reputation: 1762

SOLUTION 1

Using Proxy object you can do something like this and handle runtime defined properties

function Preferences() {
  this._preferences = {};

  var prefProxy = new Proxy(this, {
    get: function(target, property) {  
      return property in target? 
              target[property]:
              target._preferences[property];
    }

    set: function(target, property, value, receiver) {
      if(property in target){
        target[property] = value;
      } else {
        target._preferences[property] = value;
      }
    }

  });


  return prefProxy;  
};

SOLUTION 2

I can be wrong but i think what you are asking is solved returning _preferences

function Preferences () {

  this._preferences = {};

  return _preferences;
}

var obj = new Preferences()

SOLUTION 3

Using getter and setter you can redirect the property to _preferences

function Preferences () {

  this._preferences = {}

  Object.defineProperty(Preferences.prototype, 'something', {
    get: function() {
        return this._preferences['something'];
    },
    set: function(value) {
       this._preferences['something'] = value; 
    }
  });


}

var obj = new Preferences()

Upvotes: 0

loganfsmyth
loganfsmyth

Reputation: 161457

Object.defineProperty(Preferences.prototype, 'something', {
  get: function(){
    return this._preferences.something;
  },
  set: function(value){
    this._preferences.something = value;
  }
});

should do it. It defines a property, 'something', using an accessor property instead of a data property, and will call the 'get' and 'set' functions to decide what do so when .something is accessed.

Upvotes: 4

Related Questions