0

Despite this being the method approved of in several stack overflow answers, and two tutorials I've read so far, I cannot manage to call a method in javascript by dynamically generating the name without getting the console error:

Uncaught TypeError: undefined is not a function

How can I dynamically call a method?

My current code, which fails in both my Rails app and jsfiddle (you can see the fiddle here)

var foo = "hello_";
var bar = "world";
var function_name = "say_" + foo + bar;

window[function_name](" World!");

function say_hello_world(the_word)
{
    alert("Hello " + the_word);
}

Thanks in advance.

steel
  • 11,883
  • 7
  • 72
  • 109
  • 5
    It's the fiddle, http://jsbin.com/qoyuh/1/edit – elclanrs May 20 '14 at 22:24
  • you can use eval, but that might have security issues – fmodos May 20 '14 at 22:24
  • 3
    See [Simple example doesn't work on JSFiddle](http://stackoverflow.com/questions/5431351/simple-example-doesnt-work-on-jsfiddle) ... if you configure the jsFiddle correctly, it works. There you go: http://jsfiddle.net/PybGC/5/ – Felix Kling May 20 '14 at 22:26
  • duplicate of [Accessing Global Vars with Window](http://stackoverflow.com/q/20818236/218196) – Felix Kling May 20 '14 at 22:32
  • *"which fails in [...] my Rails app"* Might be the same reason as why it fails in jsFiddle: The code is inside a function that makes the variable local, not global. – Felix Kling May 20 '14 at 22:33
  • I think it's an interesting question, currently out a bunch of things. Calling a function expression dynamically is easy, but calling a function declaration, as soon as it isn't in global scope is quite a challenge (with the additional restriction not to assign it to a var of course) – Winchestro May 20 '14 at 22:58

1 Answers1

0

After parsing through the advice in the comments, and reading the articles they lead me to, it looks like JSFiddle and Rails both are declaring the function as local to onload. Explicitly declaring the function as global means this now works on both my original Fiddle and my Rails app.

var foo = "hello_";
var bar = "world";
var function_name = "say_" + foo + bar;

window.say_hello_world = function(word)
{
    alert("Hello " + word + "!");
}

window[function_name]("world");

Thanks for the help, everyone.

steel
  • 11,883
  • 7
  • 72
  • 109