2

I got this global function function:

GlobalFunctions = {
      something: function() {

      }
};

I know how to check if a function exists with this:

if (typeof functionName == "function")

or even better:

if (typeof functionName === "function")

but those I have mentioned above still return the next error when I an trying to find out if a global function is valid:

if (typeof GlobalFunctions.something == "function")

gives this:

angular.js:12520 ReferenceError: GlobalFunctions is not defined
    at r.$scope.continueLogout (my-app.js:197)
    at b.$scope.logout (my-app.js:243)
    at fn (eval at compile (angular.js:13365), <anonymous>:4:209)
    at e (angular.js:23613)
    at b.$eval (angular.js:16052)
    at b.$apply (angular.js:16152)
    at HTMLAnchorElement.<anonymous> (angular.js:23618)
    at HTMLAnchorElement.dispatch (jquery.min.js:3)
    at HTMLAnchorElement.q.handle (jquery.min.js:3)

I have searched in google but only found solutions for function but not for global functions.

Hope thats clear enough, thanks.

Raz
  • 1,910
  • 1
  • 15
  • 28

2 Answers2

2

You are not using the var / let / const key words when you declare the object.
And my guess is that your code runs with 'use strict'.

Without strict mode on, you can declare variables without the var key word and this will set the variable on the global object:

First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript mistyping a variable in an assignment creates a new property on the global object and continues to "work"

With strict mode:

'use strict'
GlobalFunctions = {
      something: function() {

      }
};

if(GlobalFunctions) console.log('yeah');

Without strict mode:

GlobalFunctions = {
      something: function() {

      }
};

if(GlobalFunctions) console.log('yeah');
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
1

Found the answer:

if (typeof GlobalFunctions != "undefined")
Raz
  • 1,910
  • 1
  • 15
  • 28