0

After reading many times this question and its accepted answer How to execute a JavaScript function when I have its name as a string

I tried to do it on my own. but I think its my unlucky day today that what I had tried was not working. I created already a fiddle for my testing

//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/

the thing I want to do is to invoke the function I declared by using string and get its return value. So I followed what I saw here in SO using the (fn==='function') argument. but it seems not working for me.

where I went wrong?

NOTE: I already check it in firebug and my function exist... Did I fall in a scoping problem? or something?

6
  • please include all relevant parts of your question in your question. Commented May 24, 2012 at 8:03
  • I think I already put the needed parts to understand my question... and there is a fiddle already... Commented May 24, 2012 at 8:04
  • jsfiddle.net/qKHpu/7 typeof fn is actually string, not function Commented May 24, 2012 at 8:04
  • @Mahan A link to an external resource does not count as "including". Commented May 24, 2012 at 8:05
  • @Mahan added my answer below :) Commented May 24, 2012 at 8:06

3 Answers 3

3

A function by name, as the related answer you mentioned says, is invoked by:

var function_name = 'alert';
window[function_name]('hello world');

See also: http://jsfiddle.net/qKHpu/4/

Sign up to request clarification or add additional context in comments.

Comments

1

http://jsfiddle.net/qKHpu/8/

You need to pass in the literal name of the function, without quotes ("), otherwise it'll be treated as a literal string, which is meaningless

alert(InvokeChecking(CheckMe)); // instead of alert(InvokeChecking("CheckMe"));

3 Comments

sorry... SO is blocking the potato... I won't forget to accept this after 7 mins
Strange, not sure who downvoted this answer ... it's also correct =/
someone downvote-stalked me :S, 16 seconds after, I got another downvote :(, o well :(
0

http://jsfiddle.net/qKHpu/27/

check it work some ..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.