Skip to content

Instantly share code, notes, and snippets.

@Reinmar
Created August 9, 2011 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Reinmar/1134905 to your computer and use it in GitHub Desktop.
Save Reinmar/1134905 to your computer and use it in GitHub Desktop.
Scope
'use strict';
console.log('--------- Scope:');
(function () {
var a = 1;
for (var a = 0; a < 10; ++a) {}
console.log('1.1:', a); // -> 10
{
var b = 1;
}
console.log('1.2:', b); // -> 1
var c_fn = function () {
var c = 1;
};
c_fn();
//console.log('1.3:', c); // -> ReferenceError
})();
console.log('--------- Lexical scoping:');
(function () {
var a = 1;
var a_fn = function () {
return a;
};
console.log('2.1:', a_fn()); // -> 1
(function (fn) {
var a = 2;
console.log('2.2:', fn()); // -> 1
})(a_fn);
(function (fn) {
a = 3;
console.log('2.3:', fn()); // -> 3
})(a_fn);
console.log('2.4:', a_fn()); // -> 3
var b = [1, 2, 3, 4],
b_i = 0;
for(; b_i < b.length; ++b_i) {
b[b_i] = function () { return b_i; };
}
console.log('2.5:', b[0]()); // -> 4
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment