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?

Community
  • 1
  • 1
Netorica
  • 18,523
  • 17
  • 73
  • 108

3 Answers3

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/

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
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"));
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
0

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

check it work some ..

vijaykumar
  • 4,658
  • 6
  • 37
  • 54