简体   繁体   中英

How do I call a nested function in a parent document from an iframe

In parent:

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

in iframe

parent.outer.inner();

does not work.

Edit: So they are private. No problem. The reason for doing this is to try and hide these functions from global scope as much as possible. I thought putting them behind a single function name with a pretty unique name would be the best way to do this.

Essentially do I need to

parent:

function outer(action){

    if(action == "inner")
       inner()

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

iframe: parent.outer("inner");

Is there a more elegant way of doing this?

Nested functions are private and you can at best only specify arguments for inner functions outside the outer function.

Explanation can be found here https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope under "Nested functions and closures"

By using closure :

   function outer(){
        function inner(){
        alert("I am Inner");
        }
        return inner ;
   }
   var x = outer();
   x();

If you want to use variable of inner function than we can do in this way :

  function outer(){
        function inner(){
         var y=10;  return y;    
       }
       return inner ;
 }
 var x = outer();
 x();

这似乎很好地回答了我的编辑问题如何将字符串转换为javascript函数调用?

One approach is using an object

function Outer(){
    this.inner = function(){
        alert("hello");
    }
}

var o = new Outer()
o.inner();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM