Last active
August 29, 2015 14:09
-
-
Save greduan/48bb89dd54dbd9cf5c83 to your computer and use it in GitHub Desktop.
Quick JS file demonstrating closures very simply
This file contains hidden or 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
var foo = 100; | |
console.log('first'); //=> 'first' | |
console.log(foo); //=> 100 | |
(function () { | |
var foo = 200; | |
console.log('second'); //=> 'second' | |
console.log(foo); //=> 200 | |
}()); | |
console.log('third'); //=> 'third' | |
console.log(foo); //=> 100 |
This file contains hidden or 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
var foo = 100; | |
console.log('first'); //=> 'first' | |
console.log(foo); //=> 100 | |
function test() { | |
var foo = 200; | |
console.log('second'); //=> 'second' | |
console.log(foo); //=> 200 | |
} | |
test(); | |
console.log('third'); //=> 'third' | |
console.log(foo); //=> 100 |
This file contains hidden or 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
var foo = 100; | |
console.log(foo); //=> 100 | |
function test() { | |
console.log(foo); //=> 100 | |
} | |
test(); | |
(function () { | |
console.log(foo); //=> 100 | |
}()); | |
console.log(foo); //=> 100 |
This file contains hidden or 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
var foo = 100; | |
console.log(foo); //=> 100 | |
(function () { | |
var bar = 200; | |
console.log(foo); //=> 100 | |
console.log(bar); //=> 200 | |
}()); | |
console.log(foo); //=> 100 | |
console.log(bar); //=> ERROR |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On the first example like you saw $foo will use the values define on its own scope.
On the second example on https://gist.github.com/Greduan/48bb89dd54dbd9cf5c83#file-closures2-js-L15 the value will be 200. This is what I ready on the script, I will run it