Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling nested function when function name is passed as a string

Tags:

javascript

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.

like image 477
SystemicPlural Avatar asked Nov 25 '10 14:11

SystemicPlural


2 Answers

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

outer("func1");
like image 90
25 revs, 4 users 83% Avatar answered Oct 08 '22 02:10

25 revs, 4 users 83%


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.

like image 25
mck89 Avatar answered Oct 08 '22 01:10

mck89