Last active
August 29, 2015 14:00
-
-
Save dtothefp/11091458 to your computer and use it in GitHub Desktop.
Lexical vs. Dynamic Scope
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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