0

I am want to acces the variable x from mainFunc through subFunc ,However i can acces variable x from global scope or from the local environment

How can i access the variable x of mainFunc from subFunc

var x = 'global x'
function mainFunc()
{
    var x = 'mainFunc x'
    console.log(x)
    console.log(this.x)

    function subFunc()
    {
        var x = 'subFunc x'
        console.log(x)
        console.log(this.x)
    }
    subFunc()
}

mainFunc()
console.log(x)
Nagaraj
  • 55
  • 1
  • 2
  • 7
  • 2
    Every time you do `var x` in a function, you are making a shadow version of the variable. A different variable of the same name. If you want access to a higher scope variable of the same name, *don't make the shadow version* – Taplar Nov 10 '20 at 21:48
  • so i have access to x of mainFunc and x of global func ,but unable to access x of mainFunc ,, is there a way where i can access that – Nagaraj Nov 10 '20 at 21:50
  • 1
    As soon as you make a shadow variable, you lose the ability to access the higher scoped variable(s) of the same name. – Taplar Nov 10 '20 at 21:51
  • so you mean it affects the lexical environment ? – Nagaraj Nov 10 '20 at 21:52
  • `this.x` inside your logic is logging the `global x` because `this` is the `window` element, and the `x` at the global scope is your outer x. Inside each function, when you declare the shadow variable, it exists in the (currently) lowest scope. So when javascript has to try to resolve it, it will find it in the lowest scope first, and have no need to try to find it at a higher scope – Taplar Nov 10 '20 at 21:54
  • so in this case there is no way i can access mainFunc x in subFunc x ? – Nagaraj Nov 10 '20 at 21:59
  • Change one to `var y` so it's not a shadow variable and you can. – Taplar Nov 10 '20 at 21:59
  • but for precisely this exact case its not possible ?? – Nagaraj Nov 10 '20 at 22:01
  • 2
    No, as previously stated. – Taplar Nov 10 '20 at 22:02

0 Answers0