简体   繁体   English

如何从iframe调用父文档中的嵌套函数

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

In parent: 在父母中:

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

in iframe 在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"); iframe:parent.outer(“内部”);

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" 可以在https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope下的“嵌套函数和闭包”下找到说明。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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