Skip to content

Instantly share code, notes, and snippets.

@ddoctorx
Created February 24, 2016 03:41
Show Gist options
  • Save ddoctorx/836f93b6b7ee3920d7ea to your computer and use it in GitHub Desktop.
Save ddoctorx/836f93b6b7ee3920d7ea to your computer and use it in GitHub Desktop.
[js-challenges-book] Self Invoking Functions 答案
var testValue;
function test() {
testValue = 3;
}();
// 问题1:
// 答案 =>
//
// SyntaxError: Unexpected token )
// 问题2:
// 答案 =>
//
// undefined
// 问题3:为什么会等于 undefined ?
// 答案 =>
//
// 因为JS执行有两个阶段(creation phase & execution phase),在执行的第一阶段(creation phase)会先把 Variable, Function definition 做 'Hosting',
// JS在做 'Hosting' 的时候会把 variables 设为 'undefined'
// 问题4:
// 答案 =>
//
!function test() { testValue = 3; }();
+function test() { testValue = 3; }();
// 为什么加上 '+' 或 `!` 可以? -- 这种方式通常是用在处理Self Invoking Functions
// '+' or '!'只是其中的选择,事实上在前面加上任何一个 `unary operator` 都可以的(例如:'-', '~', '+', '!')
// 更好的做法是把它用括号来括起来,像
(function test() { testValue = 3; })();
(function test() { testValue = 3; }());
// 为什么在前面加上 `unary operator` 就可以? --
// 在 `function(){...}` 前面加上 `unary operator` 让 JS engine 把'单号运算符'右边的部分当中expression来执行
// 更详细的解释可以在这里看到:http://stackoverflow.com/questions/13341698/javascript-plus-sign-in-front-of-function-name/13341710
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment