Recent Posts

JavaScript: variable scope

Javascript programmers are practically ranked by how well they understand scope. It can at times be quite counter-intuitive.

A globally-scoped variable

var a = 1;

// global scope
function one() {
  alert(a);
}
Local scope

var a = 1;

function two(a) {
  alert(a);
}

// local scope again
function three() {
  var a = 3;
  alert(a);
}

Intermediate: No such thing as block scope in JavaScript

var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts '4', not the global value of '1'
}
Advanced: object properties

var a = 1;

function five() {
  this.a = 5;
}
Advanced: Closure

var a = 1;

var six = (function() {
  var foo = 6;

  return function() {
    // JavaScript "closure" means I have access to foo in here,
    // because it is defined in the function in which I was defined.
    alert(foo);
  };
})();
Advanced: prototype-based scope resolution

var a = 1;

function seven() {
  this.a = 7;
}

// [object].prototype.property loses to
// [object].property in the lookup chain. For example...

// Won't get reached, because 'a' is set in the constructor above.
seven.prototype.a = -1;

// Will get reached, even though 'b' is NOT set in the constructor.
seven.prototype.b = 8;
Altogheter

// These will print 1-8
one();
two(2);
three();
four();
alert(new five().a);
six();
alert(new seven().a);
alert(new seven().b);
Global + local: An extra complex case

var x = 5;

(function () {
    console.log(x);
    var x = 10;
    console.log(x); 
})();
This will print out undefined and 10 rather than 5 and 10.

No comments:

Post a Comment