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 ...
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);
}
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);
}
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.
Related
If you have two local functions.
function a() {
alert("a");
}
function c() {
alert("c");
}
a();
and in each local function, lied another local function.
function a() {
alert("a");
b();
function b() {
alert("b");
c();
d();
}
}
function c() {
alert("c");
function d() {
alert("d");
}
}
a();
From what I understand, both functions a and c are "global" as they are first to show up in javascript. local function b is linked to global a and local d to global c, so local function b can read global function c, but are not able to see local function d as that are not global function but local function inside that global function, so it can no longer see and call local function d.
How do you ensure that function of d() can be read by the function of b();
I apologized if this has already been asked, I can't think of the correct keyword to ask, and try to search for the correct keyword does not quite answer my question. I believe the answer has to do with the return, but I never got that to work much less so use it for the function itself.
https://jsfiddle.net/Necrorifter/x1L90pvh/
Unless I am understanding or reading this wrong?
One method is to have each function return the internal functions. Then call them later on.
function a() {
console.log("a");
b();
function b() {
console.log("b");
_c = c();
_c.d();
}
return {b:b}
}
function c() {
console.log("c");
function d() {
console.log("d");
}
return {d:d}
}
a();
//i made ur code smaller cuz seeing it spaced out spaces out my mind
function a() {
alert("a");
function b() {
alert("b");
c();c(1)();//when the parameter is 1, the function d is returned, then i called the returned function(thus i called d)
}b();
}
function c(dd) {
function d() {
alert("d");
}
if(dd==1){return(d);}
alert("c");
}
a();
//there is no built in help for something like this so yea i pulled a workaround
I have a() and a b() inside that a(). I can't make any change to b() but I want to make it unable to call from outside.
So I came up with an idea to save the reference of b() and then set it to null. However, it doesn't work.
Any tips for me?
function a(){
setTimeout(b, 1000);
function b(){
console.log('called');
alert('b called');
}
window.bref = b;
console.log('finish setting');
}
a();
window.bref = null;
console.log('make b() fail to call')
Here is one approach: Enclose the function(s) in a self-executing anonymous function. This is useful so you can cache a flag that determines whether or not b() should run. Then add a static method to a() to toggle this internal flag. The example below runB is such flag. Note that no error is thrown but you can trigger an error if you need to.
(function(parent){
var runB = true;
function b(){
console.log('Executed b()');
}
function a(){
setTimeout(function(){
if(runB) {
b();
} else {
console.log('Skipped b()')
}
}, 500);
console.log('Executed a()');
}
a.disableB = function(){
runB = false;
}
parent.a = a;
})(window);
// Run it normally
a();
// Run it without b()
setTimeout(function(){
a();
a.disableB();
}, 550);
I don't know if this is good practice, but you can wrap window.bref in another function. So here I'm checking if window.bref is a function, if so, call it, or do nothing. The output of this no longer calls b().
function a(){
setTimeout(() => {
typeof window.bref === 'function' ? window.bref() : null;
}, 1000);
function b(){
console.log('called');
}
window.bref = b;
console.log('finish setting');
}
a();
window.bref = null;
console.log('make b() fail to call')
try using let:
function a(){
let b = function(){
console.log('called');
alert('b called');
}
setTimeout(b, 1000);
console.log('finish setting');
}
a();
try{b();}
catch(e){console.log("b is not called")}
function A(){
b()
c()
}
Function c has to be called after function b.
I know there's a concept in JavaScript called callback.
How do I do it in function b?
function b(cb){
//I can't put function c here, because this of c is bound to somewhere and I don't want to mess up.
}
c() will always be called after b() because you placed it there.
The real question is whether or not c() will be called before b() is finished.
If b() is not an async function, then your code is perfect. c() will be called once b() is finished.
function A(){
b(); // *not* async
c();
}
However, if b() is async in nature, you need to provide c() as a callback.
function A(){
b(c); // async
}
function b(cb){
// ...
cb(); // cb() doesn't need "this"
}
Since c() is a bound method, you need to also pass the context (this) to b().
function A(){
/* extract and save context, somehow */
b(c, context); // async
}
function b(cb, context){
// ...
cb.call(context); // cb() doesn't need "this"
}
I don't want to mess up.
If you don't want to play with context passing, you can use a Promise.
function A(){
b().then(function() {
// run "c()" only when "b()" is finished and there were no errors
c();
});
}
function b(){
// ...
// "b()" is *not* async
return Promise.resolve();
}
function b(){
// ...
// "b()" is async
var whenDone = new Promise(function(resolve, reject) {
performAsyncTask(resolve);
})
return whenDone;
}
But wait, there's more.
If you want bleeding edge tech, you can always use async/await
async function A(){
await b(); // VOILA! it's that easy
c();
}
These are the general basic strategies. Of course, you can try to mix-n-match them or try to figure out something new that suits your needs.
You can either use Promises or a callback.
In this case I'd use a callback (as it's a simple use case & promises require crossbrowser checks).
function A() {
b(c); // Pass the function 'c'
}
function c() {
// Do something else
}
function b(callback) {
// Do something
// Run callback
callback(); // This will run whatever method you passed in
}
function b(c){
doSomething();
c();
}
function a(){
b(c);
}
Your understanding is correct. The notion of the callback is when a function is complete. What you're going to have to do is to ensure that the type of input and make sure it is a function and not something different. Take a look at the following example:
function A()
{
alert('I am A function');
b(c);
}
function b(cb)
{
alert('I am "b" function');
/// At the very end, put this code:
if (typeof(cb)==='function')
{
cb();
}
}
function c()
{
alert('I am "c" function');
}
A();
Callbacks in JavaScript are functions that are passed as arguments to other functions. This is a very important feature of asynchronous programming, and it enables the function that receives the callback to call our code when it finishes a long task, while allowing us to continue the execution of the code.
var callback = function() {
console.log("Done!");
}
setTimeout(callback, 5000);
As you can see, setTimeout receives a function as a parameter, this is a callback!
In your case you can do the following:
function b(c) {
c();
}
// calling function b and sending as a parameter an anonymous function
// that will be replaced by the "c" parameter in the "b" function
b(function() {
console.log("inside c");
});
This is almost a closure, just with a little bit more tweaking and you can turn it into one.
Your question is not very clear, let me try to decipher.
If you execute
function A() { b(); c() }
function b() { /* b work */ }
function c() { /* c work */}
Then c will be called after b if by is synchronous.
In the case b is asynchronous, c will be called before b completes.
Then you need indeed a callback as a parameter of b:
function A() { b(c) }
function b(callback) { /* b work */ ; callback() }
function c() { /* c work */ }
Yet in modern js, you'd rather use a promise:
function A() {
b().then( function() {
c()
} )
}
function b() {
return new Promise( function(resolve, reject) {
/* b work */
} )
}
function c() { /* c work */ }
Say I want to do this:
function z(){return function(){a = 4}
}
function b(){
var a;
c = z();
c();
}
I want to skip the c(); But instead I want to execute the returned function immediatly upon return in the caller scope so I can work with it.
In this example a should get the value 4.
Is there a way?
cheers
You should be able to execute the return function immediately with
z()();
No, that is impossible (without using tricks like eval). You cannot change the scope of the function returned by z.
Your example could be simpler without the closure, what you are asking for is just
function c() {
a = 4;
}
function b() {
var a;
c(); // should change variable a
return a;
}
b(); // is expected to return 4, but does not
You can't alter the scopes of functions, or pass the scope objects (like pointers to the variables). Yet, you can pass an object whose properties will be altered by the function:
function z(obj) {
return function() {
obj.a = 4;
};
}
function b() {
var o = {};
z(o)(); // as mike and others said, this is the same as yours
// - you don't need the c variable
return o.a;
}
b(); // returns 4 now
escaparello did a similar thing, only he did use the object as the thisValue which he did pass to the anonymous function, not to z. I think mine is easier to understand, and makes a better use of the z closure.
Seems very strange, but you want to do something like this?
function z(){
return function() {
this.a = 4;
return this;
}
}
function b(){
var obj = { a : 0 };
var c = z().apply(obj);
console.log(c.a);
}
b();
Try this
function z(){
return function(){
return 4;
}
}
function b(){
var a;
a = z()();
}
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.
What about:
function A() {
window.B = function() {
alert("function B is running");
}
}
//CALL FUNCTION B FROM GLOBAL SCOPE
B();
You can do something like this:
function outer() {
function inner() {
// ..
}
window['inner'] = inner;
}
It's a little icky to have a direct reference to "window", so you could do this (from the global context):
(function (global) {
function inner() {
// code code code ...
}
global['inner'] = inner;
})(this);
There appear to be a couple of issues with your code
The first line doesn't appear to be legal Javascript (JSLint agrees). To declare an uninitialized variable use the var B; syntax
The code never calls A to initialize B so calling B() is invoking an uninitialized variable
I'm fairly certain the code to initialize B inside of A is also not legal.
Try the following
var B; // Establish B as a global scope variable
function A() {
B = function() {
alert('B is running');
};
}
A(); // Call the function which will cause B to be initialized
B(); // Run B
You're close, but not completely correct.
You have to define B as a variable and then assign a function to it.
Also run A() before executing B, otherwise B will be undefined. The easiest way of running it is the way that I show in my code example.
These are the smallest amount of changes to your code to make it work as you asked:
var B;
(function A() {
// define function B
B = function() {
alert("function B is running");
}
})();
// call function B globally
B();