简体   繁体   中英

How to check if a Javascript variable is defined before invoking it

I am using Cordova GA plugin to track events, but when testing in my browser I keep getting:

ReferenceError: plugin is not defined

I tried many ways to check if the plugin has been defined, but it still throws this error. How can I properly check if the plugin has been defined before I invoke the function?

To check if a JavaScript variable is undefined you can use

if (typeof myVariable === 'undefined') {
  console.log('The variable is undefined.');
}

You may simply put a check before running your code:

 if (window.plugin) {//I had assume that `plugin` is in global scope alert('plugin'); } else { alert('no plugin'); } 

Using typeof

 if('undefined' === typeof plugin) { alert('no plugin'); } else { alert('plugin ...'); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM