javascript 检查函数名称是否存在于字符串中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8592047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
check if a function exists with its name in a string?
提问by Dylan
I create functions in Javascript dynamically. Sometimes I need to check if a certain function is actually already created.
我在 Javascript 中动态创建函数。有时我需要检查某个函数是否实际上已经创建。
I have the name of the function as a string. How can I check whether a function exists based on a given value in a string?
我有一个字符串形式的函数名称。如何根据字符串中的给定值检查函数是否存在?
回答by Matt
You can check whether it's defined in the global scope using;
您可以使用以下方法检查它是否在全局范围内定义;
if (typeof window[strOfFunction] === "function") {
// celebrate
//window[strOfFunction](); //To call the function dynamically!
}
回答by Fredius
You can use eval:
您可以使用评估:
if ( eval("typeof stringFunction === 'function'") ){ /*whatever*/ }