调用函数中定义的函数 [英] Calling a function that's defined inside a function

查看:83
本文介绍了调用函数中定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*有没有办法在javaSCRIPT中的另一个函数中调用函数定义?例如:
$ b $ pre $ window.onload()= function(){
函数my_function(){
打印( 等等);
};
};

function function_two(){
my_function();
};

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

解决方案

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

  var myFunction; //这是设置范围

的占位符window.onload()= function(){
myFunction = function(){//将函数赋值给myFunction变量
print('blah');



function function_two(){
myFunction();



$ b $ p
$ b

如果你只知道myFunction所需的信息, '在onload事件中。


*Is there a way to call a function defined inside another function in javaSCRIPT? 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)? 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.

解决方案

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:

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.

这篇关于调用函数中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆