0

I need some concept of threading java script.Actually I struck in one problem .Problem is that I have one function A () calling function B and 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 
}

I need to synchronised call ...

4

3 回答 3

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);    
}
于 2013-07-17T04:55:51.053 回答
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);
}
于 2013-07-17T04:51:40.157 回答
0

实际上,它不应该undefined在函数 C 中真正发出警报。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

})();  

是的,这里与线程无关。

于 2013-07-17T05:04:46.517 回答