Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.