简体   繁体   中英

Is there a way to access variables that are only defined some of the time?

This is with 'use strict' javascript, so it's not as lax with undeclared variables. My code looks like this:

'use strict';

angular.module('myApp').factory('factoryName', function(){
   var plugins = cordova.require('cordova/plugin_list').metadata;
   ...
});

The issue I have is that the variable cordova is only defined some of the time, which causes a runtime error when it isn't. When my app is built + run on a mobile device with cordova, cordova is obviously defined so it runs fine - but it's also run on browser without cordova, which causes crashing when the code block above runs.

Is there a way around this? Like maybe to check if cordova is declared before using it? The issue is that the error that gets thrown is from an undeclared variable, rather than from reading a property of undefined, so doing if (cordova) {...} will still fail. Or is there a different way to use cordova without referencing it like this?

I would do if (typeof cordova !== 'undefined') :

 if (typeof cordova !== 'undefined') { console.log('hello'); } console.log('it didnt crash');

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