-2

There anyone try or know how to get acces to variable in anonymous function??

Example

var test = "Hi";

(function() {
    var test = "Bye";

    // Outputs "Bye"
    console.log(test);
})();

// Outputs "Hi"
console.log(test);

As you can see last log return "Hi" but i want to get "Bye" anyone know way to get value "Bye" in this example ??

2 Answers2

2

Running a function creates a scope; "Bye" is defined in this scope; and this scope is never visible from outside the function.

If you have access to the IIFE, then you can modify it so it exports this variable to the outside scope.

If this IIFE is inside a named function in the same cross-origin than your code, you can display the outer function:

var toto = function() {
    var test = "Hi";

    (function() {
        var test = "Bye";

        // Outputs "Bye"
        console.log(test);
    })();

    // Outputs "Hi"
    console.log(test);    
}

console.log(toto);

Outside from these cases, nothing can be done; by design. Even the cross-origin restriction on function code display is there to prevent you to access code that does not belong to you. Clever people have thought this through; I doubt a backdoor exists.

solendil
  • 8,432
  • 4
  • 28
  • 29
0

The only way to do that is to not recreate the variable inside the scope of the anonymous function.

var test = "Hi";

(function() {
  test = "Bye"; // notice no "var", meaning it uses the existing variable

  // Outputs "Bye"
  console.log(test);
})();

// Outputs "Bye"
console.log(test);
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67