3

I'd like to call a given function if it exists. I've written:

var backgroundPage = window.chrome && chrome.extension &&
 chrome.extension.getBackgroundPage ? chrome.extension.getBackgroundPage() : null;

I'm wondering if there's a better way to short-circuit all of those checks and only call chrome.extension.getBackgroundPage if it exists?

If I do

typeof chrome.extension.getBackgroundPage === 'function'

I will still encounter errors if chrome or chrome.extension are undefined.

In many scenarios I would be able to use a utility function such as https://lodash.com/docs#get:

var getBackgroundPage = _.get(window, 'chrome.extension.getBackgroundPage');

but for my specific scenario I'm unable to use a utility library as the full code is serving as a loader for lodash.

Sean Anderson
  • 27,963
  • 30
  • 126
  • 237
  • See here to get nested path http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key. Then check if it is a function, if so execute it. – elclanrs Sep 08 '15 at 01:42
  • There's nothing more... native? Unfortunately (ironically?), this code is serving as a loader for lodash so I don't have the ability to use a utility library in this scenario. Otherwise, it'd be pretty trivial with https://lodash.com/docs#get – Sean Anderson Sep 08 '15 at 01:46
  • You don't need a library, `get=(p,o)=>p.reduce((a,k)=>a&&a[k],o); get(['a','b','c'],{a:{b:{c:1}}}) // 1` – elclanrs Sep 08 '15 at 01:51
  • you can also pluck the method out of lodash and tuck in your own code... – dandavis Sep 08 '15 at 02:32

1 Answers1

1

That's the purpose of try...catch statement:

try {
  object.p1.p2.p3;
}
catch (e) {
  if (e.name === 'ReferenceError') {
    // pass
  }
}
Vidul
  • 10,128
  • 2
  • 18
  • 20
  • This isn't an exceptional case, though. try/catch statements should be used to help recover from unexpected scenarios not anticipated ones. http://stackoverflow.com/a/2631168/633438 – Sean Anderson Sep 08 '15 at 01:52
  • @SeanAnderson Questionable. This is an exceptional case (more than obviously), that's the sole purpose of this exception. – Vidul Sep 08 '15 at 01:55