Question

I'm trying to dynamically call a function using this code:

function myFn() {
        console.log("called");
}
var callbackName = "myFn";
console.log(window[callbackName]);

http://jsfiddle.net/Pr7B2/

However it says that window[callbackName] is undefined. Why and how can I call it dynamically? Thanks

Was it helpful?

Solution

JSFiddle wraps your JavaScript inside a function so myFn is in the local scope of another function.

Use:

window.myFn = function () {
  console.log("called");
}
var callbackName = "myFn";
console.log(window[callbackName]());

This way you explicitly define global function called myFn.

Another option (as @Barmar said) is to use the JSFiddle's option "No wrap".

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top