Skip to content Skip to sidebar Skip to footer

How Do I Use Callback To Access This Variable?

I've called myFunc inside myFunc2. Now what I want is to print var2 when I call myFunc2 using callback concept. I know something is wrong. The code I've tried isn't working. It is

Solution 1:

This is the way it works:

var a = functionmyFunc(parameter){
                var var2="another thing";
                parameter.call();
          }

    a(function(){console.log("the function parameter")})

Solution 2:

I am not that sure what you are trying to achieve. Is it something like this?

var var2;
 functionmyFunc(parameter){
    var2="another thing";
    return var2;
 }
 functionmyFunc2(){
     var var1="Something";
     myFunc(var1);
     console.log(var1);
     console.log(var2);
}
<buttononclick="myFunc2()">BUTTON</button>

You can check this Fiddle

Solution 3:

Function cannot share variable defined in their individual scope but they can share their values using arguments and return value. This is how 2 function talk.

Also remember, when you add () after a function name, it is called immediately. If you need to pass callback, you will have to pass reference (functionName).

You can refer following post: Passing parameters to a callback function for more information.

functionnewfunc(str){
  return"The test String is: " + str;
}

functionmyFunc(callback) {
  var var2 = "another thing";
  // return valuereturncallback(var2);
}

functionmyFunc2() {
  var var1 = "Something";
  // Accept value that is returned and save it in local variable// Also adding "()" after function name will call it and pass its return value as argument.// If you even need to pass reference of a function with callback, use `.bind(context, args)`var var2 = myFunc(newfunc);
  console.log(var1);
  console.log(var2);
}
<buttononclick="myFunc2()">BUTTON</button>

Snippet 2 explanation

First, defining function inside () will make it an expression and its reference will not be preserved. Due to this, your function is still not accessible.

Second, when you pass a function as a callback, it reference is shared and is available by argument name. In your case parameter. So instead of newfunc(var2) do parameter(var2)

Third, var2 does not exists inside newfunc. You are sharing value using argument (some). Use this to log.

functionmyFunc2() {
  var var1 = "Something";
  // Here newfunc will be ddestroyed after the call as it is wrapped inside ()myFunc(functionnewfunc(some) {
    console.log(some);
  });
  console.log(var1);
}

functionmyFunc(parameter) {
  var var2 = "another thing";
  parameter(var2);
}

myFunc2();

Post a Comment for "How Do I Use Callback To Access This Variable?"