2

I'm looking for a way to catch Exceptions when accessing missing properties in the object itself.

I'm looking for something like:

var objOne = 
{
    objTwo: {},
    objThree: {},
    fallback: function(missingProperty)
    {
        alert('obj did not contain property ' + missingProperty);
    }
}

Calls like objOne.objFour should be linked to objOne.fallback('objFour'). Is there a good way to handle this?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
skyscraper
  • 37
  • 3
  • You would need to write a custom getter method and not reference the properties directly. http://stackoverflow.com/a/10727950/14104 – epascarello Nov 11 '15 at 15:10

2 Answers2

1

Accessing an undefined property does not trigger any exception, you can have the same behaviour with ||:

function callBack (missingProperty) {
  alert('obj did not contain property ' + missingProperty)
}
objOne[attr] || callBack(attr);

This will trigger the callBack function when objOne does not contain attr.

Javier Conde
  • 2,553
  • 17
  • 25
0

the idea i have is to modify the constructor of the prototype of your customObject (for example objThree) and check for set values etc...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor

http://www.w3schools.com/js/js_object_definition.asp

or you define a custom event which is fired by creating an object:

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

i hope i understood you correctly and this is what you are searching for. Other possibility would be:

var objThree = function(a, b){
var parent = this;
this.valA = a;
this.valB = b;
this.checkForValues = function(){
   if (parent.valA == null || parent.valB == null) return false;
   return true;
}

greetings

messerbill
  • 5,499
  • 1
  • 27
  • 38