Access overridden global variable inside a function

回眸只為那壹抹淺笑 提交于 2019-11-27 08:03:07

问题


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 overRideX() {
      var x = "Updated";
      console.log(x);
   };

  overRideX();
}

outer();

Jsbin : Fiddle to Test

I don't want to rename the inner 'x' variable to something else. Is this possible ?

Edit: Edited question after abeisgreat answer.


回答1:


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.




回答2:


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);
}();


来源:https://stackoverflow.com/questions/15826751/access-overridden-global-variable-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!