nes*_*tor 10 javascript scope function
我将全局范围赋予嵌套JavaScript函数的尝试无效:
//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();
Run Code Online (Sandbox Code Playgroud)
这只是好奇心 - 你是对的,我没有任何理由想要这样做.
TIA - 我没有SO帐户来回复你的答案......
Fel*_*ing 15
function B; 只会生成语法错误.
您可以使用函数表达式.由于函数是第一类对象,因此可以为变量赋值:
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();
Run Code Online (Sandbox Code Playgroud)
你也可以让A一个函数返回:
function A() {
return function() {
alert("function B is running");
};
}
B = A();
Run Code Online (Sandbox Code Playgroud)
这将使之间的关系A和B更清楚一点.
当然,您可以通过省略来定义全局变量var,但是您应该非常小心地使用它.使用尽可能少的全局变量.
function A() {
B = function() {
alert("function B is running");
};
}
Run Code Online (Sandbox Code Playgroud)
我敢打赌,有一种更好的方法,取决于你的实际目标是什么.