Access overridden global variable inside a function

前端 未结 2 938
心在旅途
心在旅途 2020-12-11 18:11

I want to access global variable \'x\' when it is over-ridden by same named variable inside a function.

function outer() {
   var x = 10;
   function overRid         


        
相关标签:
2条回答
  • 2020-12-11 18:59

    The global scope of your web page is window. Every variable defined in the global scope can thus be accessed through the window object.

    var x = 10;
    function overRideX() {
        var x = "Updated";
        console.log(x + ' ' + window.x);
    }();
    
    0 讨论(0)
  • 2020-12-11 19:04

    You can use window.x to reference the globally scoped variable.

    var x = 10;
    function overRideX() {
      var x = "Updated";
      console.log(x);
      console.log(window.x);
    };
    
    overRideX();
    

    This code logs "Updated" then 10.

    0 讨论(0)
提交回复
热议问题