【发布时间】:2012-05-24 08:01:08
【问题描述】:
多次阅读此问题及其接受的答案How to execute a JavaScript function when I have its name as a string
我试着自己做。但我认为我今天不走运的一天是我尝试过的没有奏效。我已经为我的测试创建了一个小提琴
//the function I want to invoke by String
function CheckMe() {
return "haha";
}
//the function that will search for the function and invoke it
function InvokeChecking(func2check) {
var fn = func2check;
if (typeof fn === 'function') {
return = fn(); //invoke the function
}
}
//the event listener ( ´ ▽ ` )ノ
$("#checker").click(function () {
alert("event is working");
alert(InvokeChecking("CheckMe"));
});
http://jsfiddle.net/laupkram/qKHpu/2/
我要做的是调用我用字符串声明的函数并获取它的返回值。因此,我使用 (fn==='function') 参数遵循了我在 SO 中看到的内容。但它似乎不适合我。
我哪里出错了?
注意:我已经在 firebug 中检查了它并且我的函数存在......我是否陷入了范围界定问题?还是什么?
【问题讨论】:
-
请将您问题的所有相关部分包含在您的问题中。
-
我想我已经把需要的部分放在了理解我的问题上......而且已经有了一个小提琴......
-
jsfiddle.net/qKHpu/7 typeof fn 实际上是
string,而不是function -
@Mahan 指向外部资源的链接不算作“包括”。
-
哈哈哈谢谢!!!! @NiftyDude
标签: javascript oop function