2

How/Can I intercept a request to get a method/property on an javascript object and return a custom value instead.

For example,

var obj = {
    // This "get" method is where I want to replace the call to get a property of an object.
    get : function(propertyName) {
        if (propertyName == 'somePropertyThatDoesntExist') { return 1; }
        else { return 0; } // Something like this?
};

// Either this method of access,
var myValue1 = obj.somePropertyThatDoesntExist
var myValue2 = obj.someOtherPropertyThatDoesntExist

// Alternatively, 
var myValue3 = obj['somePropertyThatDoesntExist']
var myValue4 = obj['someOtherPropertyThatDoesntExist']

So myValue1 and myValue3 will have a value of 1, and myValue2 and myValue4 will have a value of 0.

Currently, myValue1, 2, 3, 4 would all be "undefined".

Ben Ellis
  • 135
  • 1
  • 7

2 Answers2

0

I don't think there is a way to intercept access to a property that is undefined. You can always do the following

if(obj.someProperty != undefined)
    obj.someProperty // access the property

alternatively, you can write a get method

var obj = {
    someProperty : "val",
    get : function(propertyName) {

        if (this[propertyName] == undefined) { return 0; }
        else { return this[propertyName]; } 
    }
};

and use it like

obj.get("someProperty") // returns 0 if property is not defined. 
U.P
  • 7,152
  • 6
  • 32
  • 58
  • don't you mean obj.get('someProperty');? – Ben Ellis Mar 01 '13 at 13:15
  • I'm trying to replace an existing object and I can't replace the javascript code that calls it, so obj.get('') and checking if it is undefined in the client code aren't options for me. – Ben Ellis Mar 01 '13 at 13:15
  • @BenElis sorry, it was a typo. Fixed it. Well, in that case, this technique won't work – U.P Mar 01 '13 at 13:26
0

This is possible in JavaScript ES6 using the Proxy object

var obj = {}

// Wrap the object using Proxy
obj = new Proxy(obj, {
  get : function (target, propertyName) {
    if (propertyName === 'somePropertyThatDoesntExist') { return 1; }
    else { return 0; }
  }
})

var myValue1 = obj.somePropertyThatDoesntExist       // 1
var myValue2 = obj.someOtherPropertyThatDoesntExist  // 0
Emil
  • 11
  • 2