0

I would like to handle undefined properties and/or identifiers on my object before they fail/return undefined if that is possible.

Is there a neat way to capture the access to a non-defined property and handle it without using try/catch?

var myObj = {
    myVar : 10,
    myFunc : function(){console.log('foo')
}

myObj.myVar;
myObj.myFunc();

var x = "myFunc";
myObj[x];
x = "myOtherFunc";
// Handle this in an eventhandler or similar before it fails!?!?
myObj[x];

I can not alter the calling code from my position. I can only change the code inside myObj, since its a module used by others.

Flexo
  • 2,506
  • 3
  • 21
  • 32
  • What fails exactly? You can get an undefined properties from an object without error -- `console.log({}.foo) // undefined`. If you need to work with the value, you can see if it exists first: `if (x in myObj) myObj[x]...` [Determining if a javascript object has a given property](http://stackoverflow.com/questions/1894792/determining-if-a-javascript-object-has-a-given-property). – Jonathan Lonowski Mar 11 '14 at 13:33
  • Nope, there's nothing like [`__call`](http://www.php.net/manual/en/language.oop5.overloading.php#object.call) in javascript, keep track of what you have and you should be fine. – adeneo Mar 11 '14 at 13:33
  • @JonathanLonowski Well, i am in a position where i cannot alter the code outside myObj and therefore i cannot check if x exist in myObj before i call it. – Flexo Mar 11 '14 at 13:36

2 Answers2

0
try {
  myObj.myOtherFunc();
} catch() {

}

myObj.myOtherFunc() || ""; //default value;

myObj.myOtherFunc() || myObj.myDefinedFunc(); //default value;

if (var t = myObj.myOtherFunc())
  // something
else
  // something else
wayne
  • 3,410
  • 19
  • 11
  • Thank you for the answer, however, this wont work for me since i can not change the calling code. I can only change the code inside myObj – Flexo Mar 11 '14 at 14:04
0

try this:

if(myObj.hasOwnProperty(x)) {
    myObj[x];
}
Fredster
  • 146
  • 1
  • 1
  • 7
  • Edited question to explain why your answer wont work for my case. Fair answer to solve to problem in general though. – Flexo Mar 11 '14 at 14:03