Reputation: 171341
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!");
}
Upvotes: 0
Views: 232
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
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
Reputation: 444
Your code works if you change the way you declare the function (if you can do that)
foo = function() {
alert("foo called");
}
Upvotes: 0
Reputation: 2382
Try with window[func_name] instanceOf Function or you can use jquery.isFunction method
Upvotes: 0
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
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
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