How does JavaScript read the variables with the same names?



  • There are three variables with the same name (value), but with different values. How can all three variables be read out of this function?

    (the question is not practical, but theoretical, so the proposals to name them in different ways, transmit them in terms of functions, etc., are not appropriate. What you want to understand is to use the AS 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
    }
    

    }

    ActionScript is easy enough:

    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, an activation facility can be used (but in JS as far as I know 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()



  • C global everything is easy, there's a window on the ground. The internal is clear, too, so don't think so much. And from the outside, you're gonna have to use khaki, like 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);
    }
    

    }

    P.S., although I think you'll never get a "external" inside, because the reference is instantly blurted with one mention. var value




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2