开发者

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

开发者 https://www.devze.com 2023-04-08 16:20 出处:网络
Given a function name as a string, how could I determine if such function exist (globally), and if yes, call to this function ?

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.


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() ...


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


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

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

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


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


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

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

JSFIDDLE


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号