简体   繁体   English

调用在 function 中定义的 function

[英]Calling a function that's defined inside a function

*Is there a way to call a function defined inside another function in javaSCRIPT? *有没有办法调用 javaSCRIPT 中另一个 function 中定义的 function? For example:例如:

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)?有没有办法做类似上面的事情(在 function_two 中调用 my_function,即使它是在 window.onload() 函数中定义的)? 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). 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() (像我的函数)。 However the console says that the my_function is undefined.但是控制台说 my_function 是未定义的。

The scope of the function is the core issue here, as Zeychin and Trevor have said.正如 Zeychin 和 Trevor 所说,function 的 scope 是这里的核心问题。 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:基本上,您可以将 function 设置为位于更高 scope 中的变量(即, onload 和 function_two 函数都可以访问),同时在 onload ZC1C425268E68385D1AB5074C 中定义它最初有:

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 所需的信息,这可能会很方便。

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

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

function function_two(){
    my_function();
};

You can not do what you are asking to do.你不能做你要求做的事。 The function my_function() 's scope is only within the anonymous function, function() . function my_function()的 scope 仅在匿名 function, function()内。 It falls out of scope when the method is not executing, so this is not possible.当方法未执行时,它会脱离 scope,因此这是不可能的。 Trevor's answer is the way to do this.特雷弗的回答是做到这一点的方法。

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

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