我需要一些线程化java脚本的概念。实际上我遇到了一个问题。问题就是这样 我有一个函数A()调用函数B和C.
function A(){
B();
C();
}
function B(){
//doing some task
i=something;
alert(i);
}
function C(){
// i need value I here.
alert(i) //getting undefined
}
我需要同步通话......
答案 0 :(得分:5)
怎么样
function A(){
C(B());
}
function B(){
//doing some task
var i=something;
return i;
}
function C(i){
// i need value I here.
alert(i)
}
或拆分以提高可读性
function A(){
var resultFromB = B(); //
C(resultFromB);
}
function B(){
//doing some task
var result=something;
return result; // return it to calling function
}
function C(resultOriginallyFromB) { // passing it
alert(resultOriginallyFromB);
}
答案 1 :(得分:1)
将i
设置为全局,
var i=null;// global i
function A(){
B();
C();
}
function B(){
//doing some task
i=something;
alert(i);
}
function C(){
i need value I here.
alert(i) //getting undefined
}
或者,您可以在return
中使用B()
,
function A(){
i=B();
C(i);//passing i in C()
}
function B(){
//doing some task
i=something;
alert(i);
return i;//return i
}
function C(i){
// value i has been passed in.
alert(i);
}
答案 2 :(得分:0)
实际上它不应该在功能C中提醒undefined
。i
已经全局定义,而不使用var
。
除了尝试这样做,这样你就不会混淆全局空间:
(function() {
var i;
function A(){
B();
C();
}
function B(){
//doing some task
i=4; // --- or something
alert(i); // --- will alert 4
}
function C(){
// i need value I here.
alert(i) // --- will alert 4
}
A(); // --- Assuming you were calling 'A' earlier as well
})();
是的,这里没有与线程相关的内容。