There are three variables with the same name (value), but with different values. How can one of these three variables be read from a nested function?

(the question is not practical, but theoretical, so the proposals to call them differently, pass in the parameters taken by functions, etc. do not fit. What you want to understand is to use it by analogy with AS - examples below)

var value = "global" function f1() { var value = "external"; function f2() { var value = "internal"; alert(any code 1?) // global alert(any code 2?) // external alert(any code 3?) // internal } } 

In ActionScript, this is pretty easy:

 var _value = "global" function f1() { var _value = "external"; function f2() { var ext=_value var _value = "internal"; trace(_root._value) // works: global trace(ext) // works: external trace(_value) // works: internal } f2() } f1() 

Also in ActionScript, you can use an activation object (but in JS as far as I know there is no access to it):

 var _value = "global" function f1() { var _value = "external"; function f2() { _value // связываем объект активации f1 с f2 var _value = "internal"; trace(_root._value) // works: global trace(this._value) // works: external trace(_value) // works: internal } f2() } f1() 
  • 2
    call them differently. - Darth
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

3 answers 3

C global is easy, the window object is in place of the root. With internal, everything is also clear, there is no need to think too much. But with external it is necessary to use hacks, as well as in AS.

 var value = "global" function f1() { var value = "external"; var val = value; function f2() { var value = "internal"; console.log(window.value); console.log(val); console.log(value); } } 

PS although it seems to me that inside f2 you will not get "external", since the link is instantly overwritten at the mere mention of var value .

    You can use this interesting JavaScript feature as a closure:

     var value = "global"; function f1() { var value = "external"; var f1_value = function() { return value; }; function f2() { var value = "internal"; document.body.innerHTML = window.value + "<br />" + // global f1_value() + "<br />" + // external value; // internal } f2(); } 
     <body onload="f1();"> </body> 

      You can simply call f2 with the value parameter.
      Output "global external internal"

       var value = "global"; function f1() { var value = "external"; function f2() { var value = "internal"; alert(window.value + " " + arguments[0] + " " + value); } f2(value); } f1();