Misha Moroshko
Misha Moroshko

Reputation: 171341

How to determine if a function with a given name exist in Javascript / jQuery?

Given a function name as a string, how could I determine if such function exist (globally), and if yes, call to this function ?

I tried to do:

function foo() {
    alert("foo called");
}

var func_name = "foo";

if (typeof window[func_name] == 'function') {
  foo();
} else {
  alert(func_name + " is not defined!");
}

But, it doesn't seem to work.

Upvotes: 0

Views: 232

Answers (7)

attila
attila

Reputation: 46

I suggest you not to use the typeof variable === 'function', I prefer a function for checking a type, instead of the regular type checking. This approach saved me and my colleagues life many times. For example:

isFunction = function(val) {
    return typeof val == 'function' && val.call !== 'undefined';
};

window.foo = function() {
    alert("foo called");
};

var func_name = "foo",
    /*for testing purpose*/fn = foo; // fn = window[func_name];

if (isFunction(fn)) {
    fn();
}
else {
    alert(func_name + 'is not defined!');
}

ps: the provided example is not the most perfect version of checking a function type because in IE cross-window calls function appears as object.

Upvotes: 0

Jan Pfeifer
Jan Pfeifer

Reputation: 2861

This should help you

if(typeof myFunctionName == 'function') myFunctionName()

Look at this link to seemore info about typeof operator

UPDATE

if(eval("typeof window."+myFnName) == 'function') eval(myFnName+"()");

But like the others stated, your original code works as expected.

Upvotes: -1

Jose Antonio
Jose Antonio

Reputation: 444

Your code works if you change the way you declare the function (if you can do that)

foo = function() {
    alert("foo called");
}

JSFIDDLE

Upvotes: 0

malko
malko

Reputation: 2382

Try with window[func_name] instanceOf Function or you can use jquery.isFunction method

Upvotes: 0

Alnitak
Alnitak

Reputation: 339816

The reason your jsfiddle doesn't work is because the named function has been defined within jsfiddle's default onLoad wrapper.

This means that the function is only defined within the scope of that closure, and isn't added to the global object.

For testing purposes, just add your function explicitly to the global object by declaring it as:

window.foo = function() ...

Upvotes: 5

Skylar Anderson
Skylar Anderson

Reputation: 5703

I took a look and it seems to work in my browser console, but not in the fiddle. I was able to get it to work in fiddle by explicitly attaching the function to window:

window.foo = function() {
    alert("foo called");
}

Upvotes: 2

Vlad Balmos
Vlad Balmos

Reputation: 3412

function foo() {
    alert("foo called");
}

var func_name = "foo";
var funcObj = null;

try {
funcObj = eval(func_name);
funcObj();
} catch(e) {
    // no function defined
}

Upvotes: 0

Related Questions