Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check a variable is local or global in JavaScript?

Tags:

javascript

When executing a JavaScript function, how can I decide the used variable is local or global?

Because I only want to record the modification to the global variable.

<script>
   var a;
   a =4;

   function foo(){
       var a =3;
   }()

</script>

when executing the above code, I only want to record the a=4, not a=3;

like image 922
user2751079 Avatar asked Oct 23 '25 09:10

user2751079


1 Answers

<script>
  var a;
  a = 4;
  function foo(){
    // version 1:
    if (window.hasOwnProperty('a')){
      // "global" a exists
    }
    // version 2:
    if (typeof window.a !== 'undefined'){
      // "global" a exists and is defined
    }
  }();
</script>

Something like that?

like image 113
Brad Christie Avatar answered Oct 24 '25 22:10

Brad Christie