What is the scope of variables in JavaScript? -


what scope of variables in javascript? have same scope inside opposed outside function? or matter? also, variables stored if defined globally?

i think best can give bunch of examples study. javascript programmers practically ranked how understand scope. can @ times quite counter-intuitive.

  1. a globally-scoped variable

    var = 1;  // global scope function one() {   alert(a); // alerts '1' } 
  2. local scope

    var = 1;  function two(a) {   alert(a); // alerts given argument, not global value of '1' }  // local scope again function three() {   var = 3;   alert(a); // alerts '3' } 
  3. intermediate: no such thing block scope in javascript (es5; es6 introduces let)

    a.

    var = 1;  function four() {   if (true) {     var = 4;   }    alert(a); // alerts '4', not global value of '1' } 

    b.

    var = 1;  function one() {   if (true) {     let = 4;   }    alert(a); // alerts '1' because 'let' keyword uses block scoping } 
  4. intermediate: object properties

    var = 1;  function five() {   this.a = 5; }  alert(new five().a); // alerts '5' 
  5. advanced: closure

    var = 1;  var 6 = (function() {   var = 6;    return function() {     // javascript "closure" means have access 'a' in here,     // because defined in function in defined.     alert(a); // alerts '6'   }; })(); 
  6. advanced: prototype-based scope resolution

    var = 1;  function seven() {   this.a = 7; }  // [object].prototype.property loses // [object].property in lookup chain. example...  // won't reached, because 'a' set in constructor above. seven.prototype.a = -1;  // reached, though 'b' not set in constructor. seven.prototype.b = 8;  alert(new seven().a); // alerts '7' alert(new seven().b); // alerts '8' 

  7. global+local: an complex case

    var x = 5;  (function () {     console.log(x);     var x = 10;     console.log(x);  })(); 

    this print out undefined , 10 rather 5 , 10 since javascript moves variable declarations (not initializations) top of scope, making code equivalent to:

    var x = 5;  (function () {     var x;     console.log(x);     x = 10;     console.log(x);  })(); 
  8. catch clause-scoped variable

    var e = 5; console.log(e); try {     throw 6; } catch (e) {     console.log(e); } console.log(e); 

    this print out 5, 6, 5. inside catch clause e shadows global , local variables. special scope caught variable. if write var f; inside catch clause, it's same if had defined before or after try-catch block.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -