JavaScript - 为嵌套函数声明全局范围? [英] JavaScript - Declaring Global Scope for Nested Function?
问题描述
//在全局范围内声明函数B
函数B;
函数A(){
// DEFINE FUNCTION B INSIDE NEST
B(){
alert(function B is running);
}
}
//从全局范围调用函数B
B();
这只是好奇心 - 你说的没错,我没有任何理由这样做。
TIA - 我没有SO帐户来回答您的答案...
>您可以使用 函数表达式 一>。由于函数是第一类对象,因此可以将函数分配给变量:
var B; //声明(全局)变量(外部作用域)
函数A(){
//为它分配一个函数
B = function(){
alert (功能B正在运行);
};
}
//我们必须调用A,否则它将无法工作
A();
//调用B
B();
您也可以让 A
返回一个函数:
函数A(){
返回函数(){
alert(函数B正在运行);
};
}
B = A();
这会使 A
和 B
有点清晰。
当然,你可以通过省略来定义一个全局变量, var
,但你应该非常小心地使用它。
$ b
函数A(){
B = function(){
警报(功能B正在运行);
};
}
我敢打赌,有一种更好的方法可以做到这一点,实际目标是。
My attempts at giving global scope to a nested JavaScript function are not working:
//DECLARE FUNCTION B IN GLOBAL SCOPE
function B;
function A() {
//DEFINE FUNCTION B INSIDE NEST
B() {
alert("function B is running");
}
}
//CALL FUNCTION B FROM GLOBAL SCOPE
B();
This is just curiosity -- you are correct that I don't really have any good reason to want to do this.
TIA -- I don't have an SO account to respond to your answers...
function B;
will simply generate a syntax error.
You can use a function expression. As functions are first class objects, you can assign a function to a variable:
var B; // declare (global) variable (outer scope)
function A() {
// assign a function to it
B = function() {
alert("function B is running");
};
}
// we have to call A otherwise it won't work anyway
A();
// call B
B();
You could also let A
return a function:
function A() {
return function() {
alert("function B is running");
};
}
B = A();
This would make the relation between A
and B
a bit clearer.
Of course you can always define a global variable by omitting var
, but you should use this very carefully. Use as less global variables as possible.
function A() {
B = function() {
alert("function B is running");
};
}
And I bet there is a better way of doing it, depending on what your actual goal is.
More about Functions and function scope.
这篇关于JavaScript - 为嵌套函数声明全局范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!