Declare a variable in another scope

Take a look at this cut off code:

main = function() {
  alert('This is ' + T);
}

caller = function() {
  var T = 'me';
  main();
}

caller();

as you can see, I want the main function to determine the value of the variable T, but the browser shows this error: T - undefined.

I can handle this error by changing the scope of the T variable to the global scope, or even pass the T variable to main, but for some reason I don’t want to use it, and I want to declare the T variable in the scope of the main function. Is this possible or not? How can I handle this scenario?

Thanks.

+1
source share
8 answers

I think something like this can handle this.

main = function() {
  alert('This is ' + T);
}

caller = function() {
  var T = 'me';
  eval('var func = ' + main);
  func();
}

caller();
0
source

You have 3 options:

  • declare T outside of both
  • pass T to main (T) as parameter
+6

T - caller, main, - T caller main

T

main = function(T) {
  alert('This is ' + T);
}

caller = function() {
  var T = 'me';
  main(T);
}

caller();

T , main main

+3

, , .

- :

caller = function() {
  var T = 'me',
      main = function() {
        alert('This is ' + T);
      };
  main();
}

caller();

, , . this Function.prototype.call Function.prototype.bind:

main = function() {
  alert('This is ' + this);
}

caller = function() {
  var T = 'me';
  main.call(T);
}

caller();

main = function() {
  alert('This is ' + this);
}

caller = function() {
  var T = 'me',
      newMain = main.bind(T);
      newMain();
}

caller();
+2

- , T, main caller. , ,

var pair = (function() { 
  var T;
  var main = function() { 
    alert('This is ' + T);
  };
  var caller = function() { 
    T = 'me';
    main();
  };
  return { 'main': main, 'caller': caller}
})();

pair.main(); // Call main
pair.caller(); // Call caller
+1

T this

main = function() {
   alert('This is ' + this);
}

caller = function() {
   var T = 'me';
   main.call(T);
}

caller();
+1

:

  • T global;
  • getter
  • T
0

var T = '';
main = function() {
  alert('This is ' + T);
}

caller = function() {
  T = 'me';
  main();
}

caller();
0

Source: https://habr.com/ru/post/1722775/


All Articles