5

I'm trying to access a nested function by passing the function name in as a string and then calling it. Eg, see this post

function outer(action){
    window["outer"][action]();

    function inner(){
        alert("hello");
    }
}
outer("inner");

However it doesn't work. Error:

window.outer[action] is not a function

How to make this work, or an alternative way of calling a nested function.

The reason for this is that I am trying to hide a bunch of functions that are called by an iframe inside a functions scope.

Community
  • 1
  • 1
SystemicPlural
  • 5,299
  • 7
  • 46
  • 69

2 Answers2

6
function outer(action){
   var inner = {
     func1: function() {},
     func2: function() {},  
     func3: function() {},
     // ...
   }
   inner[action]();
}

outer("func1");
gblazex
  • 47,726
  • 12
  • 95
  • 89
1

In that way you are trying to access the "inner" property of the "outer" function (outer.inner) that is not defined. The only way to do that is by using eval:

function outer(action){
    eval(action+"()");

    function inner(){
        alert("hello");
    }
}
outer("inner");

But remember eval is evil is some situations so be careful.

mck89
  • 18,377
  • 15
  • 87
  • 103