How to determine if a JavaScript function is defined?

I want to check if a function is defined (I don't care how, I mean, it can be used)

code example:

var functions = {
    'alert':'alert',
    'undefinedFunction':'undefinedFunction',
    'ff.showAlert':'ff.showAlert'
};

var ff = {
    showAlert: function() {
        alert('the function works');
    }
};

for (i in functions) {
    console.log(i+' : '+typeof window[functions [i]]);
}

this returns:

alert : function
undefinedFunction : undefined
ff.showAlert : undefined

console.log(typeof window.ff.showAlert); return function

demo
Is there a way to programmatically check if a function exists?

+3
source share
5 answers

The code:

window[functions [i]]

Checks for availability window['ff.showAlert'], but you really want to check:

window['ff']['showAlert']

or

window.ff.showAlert

To do this, you need to go through the namespace ( windowff→ ...):

function methodIsDefined(fn, obj) {
  var ns = fn.split('.');
  fn = ns.pop();
  do {
    if (!ns[0]) {
      return typeof obj[fn] === 'function';
    }
  } while(obj = obj[ns.shift()]);
  return false;
}

eg.

methodIsDefined('ff.showAlert', window); // => true
methodIsDefined('ff.foo', window); // => false
+6
source

. "ff.showAlert" window['ff']['showAlert'], window['ff.showAlert'], . , , window['ff']['showAlert']. , , , .

, , DOM, . ( !):

function checkFunction( name ) {

  var path = "ff.showAlert".split( '.' ),
      runner = window;

  for( var i=0; i<path.length; i++ ) {
    if( path[i] in runner ) {
      runner = runner[ path[i] ];
    } else {
      return false;
    }
  }
  return runner;
}

@VirtualBlackFox : , ​​ window -scope. , .

, , , .

+2

, 'ff.showAlert'. , ff var, window, . , .

, , , window, :

function isFnDefined(fnName, baseObj) {
    try {
        var parts = fnName.split('.'),
            ii;

        // If no baseObj was provided, default to 'window'.
        baseObj = baseObj || window;

        for (ii in parts) {
            baseObj = base[parts[ii]];
        }

        return typeof baseObj === 'function';
    }
    catch (e) {
        return false;
    }
}​

isFnDefined('alert');          // returns true
isFnDefined('undefinedFunc');  // returns false
isFnDefined('ff.showAlert');   // returns true, if ff is a member of window 
isFnDefined('showAlert', ff);  // returns true
0

, - , , , , .

var f = undefined;
try
{
    f = eval(functions[i]);
}
catch(ReferenceError) {}
console.log(typeof f);

But why do you store strings instead of yourself in your original object?

Also, if you can make each line be a link relative to the window (there is no "var" in the current area or something that comes from closing another area), then @Sirko might be the best.

-2
source

All Articles