Skip to content

Instantly share code, notes, and snippets.

@dtothefp
Last active August 29, 2015 14:00
Show Gist options
  • Save dtothefp/11091458 to your computer and use it in GitHub Desktop.
Save dtothefp/11091458 to your computer and use it in GitHub Desktop.
Lexical vs. Dynamic Scope
// Lexical
(function(){
function addIt(){
var x = 100;
function addInside(){
return x += 5;
}
return addInside();
}
console.log(addIt());
}());
// Dyanamic
(function(){
function addDynamic(){
return x += 5;
}
function dynamic1(){
var x = 1;
return addDynamic();
}
function dynamic2(){
var x = 100;
return addDynamic();
}
// This will fail unless we make a global to this closure, of x
// dynamic1();
// dynamic2();
var x = 100;
console.log(dynamic1()); // 105
console.log(dynamic2()); // 110 because x is incremented by dynamic1
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment