Skip to content

Instantly share code, notes, and snippets.

@Pindar
Created November 1, 2012 16:51
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 Pindar/3994991 to your computer and use it in GitHub Desktop.
Save Pindar/3994991 to your computer and use it in GitHub Desktop.
JavaScript special
/*
* http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/
*/
alert(x); // function
var x = 10;
alert(x); // 10
x = 20;
function x() {}
alert(x); // 20
/*
* http://dmitrysoshnikov.com/ecmascript/es5-chapter-3-2-lexical-environments-ecmascript-implementation/
* This is why, closures formed as function declarations (FD) save the VariableEnvironment component as their [[Scope]] property,
* and function expressions (FE) save exactly LexicalEnvironment component in this case. This is the main (and actually the only)
* reason of separation of these two, at first glance the same, components.
*/
var a = 10;
with ({a: 20}) {
// FD
function foo() { // do not test in Firefox!
console.log(a);
}
// FE
var bar = function () {
console.log(a);
};
foo(); // 10!, from VariableEnvrionment
bar(); // 20, from LexicalEnvrionment
}
foo(); // 10
bar(); // still 20
/* http://www.2ality.com/2012/01/object-plus-object.html */
[] + [] // ''
[] + {} // [object Object] ('' + String({}))
{} + {} // NaN (empty block Number({}) )
({} + {}) // [object Object][object Object] (is an expression)
{} + [] // 0 (empty block + [] -> Number(''))
/* FDs */
/* FD must not be defined within a block, but each browser is this supporting in a different implementation */
if (true) {
function foo() {
console.log("if foo");
}
} else {
function foo() {
console.log("else foo");
}
}
foo();
/* closure */
var x = "global";
var o = (function () {
var x = "local";
function closure() {
return x;
}
var g = new Function('return x;'); // has always the global scope.
return {
closure: closure,
g: g
};
}());
o.closure();
"local"
o.g();
"global"
/* IE anomalies */
var foo = function bar() {
console.log("function");
}
foo(); // function
bar(); // < IE 9: "function"; >= IE 9: "bar" is undefined;
// with the identical names
console.log(foo); // < IE 9: prints the definition of the function. >= IE9: undefined
var foo = function foo() {
console.log("function");
}
foo(); // "function"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment