Javascript 调用在函数内部定义的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6784079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:10:03  来源:igfitidea点击:

Calling a function that's defined inside a function

javascriptfunction

提问by tkrishnan

*Is there a way to call a function defined inside another function in javaSCRIPT? For example:

*有没有办法调用javaSCRIPT中另一个函数中定义的函数?例如:

window.onload() = function() {
    function my_function(){
        print("Blah");
    };
};

function function_two(){
    my_function();
};

Is there a way to do something like the above (calling my_function in function_two even though it's defined inside the window.onload() function)? In my actual code, which also uses the raphael.js library, I'm trying to write a button in HTML, which using the onClick function, calls a function(like function_two) that runs the function defined in window.onload() (like my_function). However the console says that the my_function is undefined.

有没有办法做类似上面的事情(在 function_two 中调用 my_function 即使它是在 window.onload() 函数中定义的)?在我的实际代码中,它也使用了 raphael.js 库,我试图在 HTML 中编写一个按钮,它使用 onClick 函数调用一个函数(如 function_two),该函数运行在 window.onload() 中定义的函数(像 my_function)。但是控制台说 my_function 未定义。

回答by Ben Hull

The scope of the function is the core issue here, as Zeychin and Trevor have said. I thought I'd offer another way of handling it. Basically, you can set your function to a variable that's in a higher scope (that is, accessible to both the onload and function_two functions), while defining it inside the onload function as you originally have:

正如 Zeychin 和 Trevor 所说,函数的范围是这里的核心问题。我想我会提供另一种处理方式。基本上,您可以将函数设置为更高范围内的变量(即,onload 和 function_two 函数都可以访问),同时在 onload 函数中定义它,就像您最初拥有的那样:

var myFunction; //This is the placeholder which sets the scope

window.onload() = function() {
   myFunction = function() { //Assign the function to the myFunction variable
      print('blah');
   }
}

function function_two() {
   myFunction();
}

This might be handy if you only know the information you need for myFunction once you're in the onload event.

如果您只知道进入 onload 事件后 myFunction 所需的信息,这可能会很方便。

回答by Trevor

window.onload = function() {
    my_function()
};

function my_function(){
    alert("Blah");
};

function function_two(){
    my_function();
};

回答by Zéychin

You can not do what you are asking to do. The function my_function()'s scope is only within the anonymous function, function(). It falls out of scope when the method is not executing, so this is not possible. Trevor's answer is the way to do this.

你不能做你要求做的事。函数my_function()的作用域仅在匿名函数内function()。当方法没有执行时,它超出了范围,所以这是不可能的。特雷弗的回答就是这样做的方法。