Testing for undefined and null child objects in ActionScript / Flex
I use this pattern to test undefined and null values โโin ActionScript / Flex:
if(obj) {
execute()
}
Unfortunately, ReferenceError is always thrown when I use a template to validate child objects:
if(obj.child) {
execute()
}
ReferenceError: Error #1069: Property child not found on obj and there is no default value.
Why does testing child objects with if statements raise a ReferenceError?
Thanks!
a source to share
You are getting this error because the obj type has no child property in it. You need to do something like this:
if((obj) && (obj.hasOwnProperty('child') && (obj.child)){
execute()
}
More information about the hasOwnProperty method in the Object class: http://livedocs.adobe.com/flex/3/langref/Object.html#hasOwnProperty%28%29
a source to share
This happens when it obj
is a strongly typed object but has no field child
.
You can check if a field exists for any object using the operator in
:
if ("foo" in obj && obj.foo)
execute();
I also wrote a utility function to make this process easier:
function getattr(obj:Object, field:*, dflt:*=undefined):* {
if (field in obj && obj[field])
return obj[field];
return dflt;
}
a source to share
You can avoid pivot errors by using array notation:
if([obj.name][child.name]){
execute();
}
It's important to understand that simply fixing the error can lead to road problems - debugging will be more difficult in larger applications.
Of course, the ideal approach is to completely avoid the situation by using validator functions to make sure you have the correct data, instead of checking for null when the data is required. :)
a source to share