/* ================== */ /** * Concepts: * Global Context * Chained Assignment */ var x = 1; var y = 2; var z = 3; !function init() { var x = y = z = 10; }() alert(x); // 1 alert(y); // 10 alert(z); // 10 /* ================== */ /* * Concepts: * Scope Chain * Object * Prototype Chain */ var foo = function () {}, bar = function () { this.a = '1'; }; foo.prototype.a = '2'; function main() { foo.a = '3'; Object.prototype.a = '4'; return function inner() { alert(foo.a); // 3 alert(bar.a); // 4 alert(new foo().a); // 2 alert(new bar().a); // 1 } } main()(); /* ================== */ /** * Concepts: * Execution Context */ (function () { alert(foo); // function pointer alert(bar); // undefined var foo = 'hello', bar = function () { return 'world'; }; function foo() { return 'hello'; } })() /* ================== */ /* * Concepts: * Lexical Scope */ var foo = 1; function static() { alert(foo); // 1 } !function () { var foo = 2; static(); }(); /* ================== */ /* * Concepts: * Bind function */ this.x = 9; var module = { x: 81, getX: function () { return this.x; } }; var getX = module.getX; getX(); // 9 var boundGetX = getX.bind(module); boundGetX(); // 81 /* ================== */ /** * Concepts: * Eval function */ var foo = 10; (function (x) { var eval = x; var foo = 20; return [x('foo'), eval('foo')] })(eval) /* ================== */ /** * Concepts: * If ... else ... * * Reference: * http://javascript.ruanyifeng.com/grammar/basic.html */ var m = 1; var n = 2; if (m !== 1) if (n === 2) console.log('hello'); else console.log('world'); /* --------------- * References: * 1. http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/ * 2. http://davidshariff.com/blog/javascript-scope-chain-and-closures/ * 3. http://wingolog.org/archives/2012/01/12/javascript-eval-considered-crazy * 4. http://www.zhihu.com/question/20032419 * 5. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind */