user2563256
user2563256

Reputation: 187

Need some concept of threading in java script?

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 ...

Upvotes: 0

Views: 89

Answers (3)

mplungjan
mplungjan

Reputation: 177786

How about

function A(){
   C(B());
}

function B(){
   //doing some task 
   var i=something;
   return i;
}

function C(i){
   // i need value I here.
   alert(i)    
}

or split out for readability

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);    
}

Upvotes: 5

loxxy
loxxy

Reputation: 13151

Actually it should not really be alerting undefined in function C. As i would have become globally defined already, without the use of var.

Besides try doing it this way, so that you don't clutter the global space:

(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

})();  

And yes, nothing related to threading here.

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Set i as global like,

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 
}

Read this also

Alternatively, you can use return in B() like,

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);
}

Upvotes: 1

Related Questions