jeudi 12 février 2015

Dependent Object Type Check Javascript Seems Redundant


Is there a better way of doing this?


If I do this:



if(typeof someObject[bar][foo] == "function"){
// Do something
}


I get a someObject[bar][foo] is not an object error which it's referring to someObject[bar] if bar does not exist. This means that the code assumes you know that someObj[bar] is defined. So my solution was was this:



if(typeof someObj[bar] === "object"){
if(typeof someObject[bar][foo] == "function"){
// Do something
}
}


If we want to make an effort to reduce code lines and to make good, clean, readable code then looks redundant and ugly. Is there a better way of doing this without having to go through two if points? I realize that it's not that big of a deal, but I'm wondering if there is a better way.





Aucun commentaire:

Enregistrer un commentaire