Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a JavaScript function is defined?

Tags:

javascript

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

sample code:

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

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

like image 481
ilyes kooli Avatar asked Feb 05 '26 13:02

ilyes kooli


1 Answers

The code:

window[functions [i]]

Is checking for window['ff.showAlert'] but what you really want to check for is:

window['ff']['showAlert']

or

window.ff.showAlert

For this, you need to traverse the namespace (window->ff->...):

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;
}

E.g.

methodIsDefined('ff.showAlert', window); // => true
methodIsDefined('ff.foo', window); // => false
like image 147
James Avatar answered Feb 08 '26 03:02

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!