JavaScript quirk 6: the scope of variables
来源:互联网 发布:网络交易平台刷赞自动 编辑:程序博客网 时间:2024/05/17 03:12
[This post is part of a series on JavaScript quirks.]
In most programming languages, variables only exist within the block in which they have been declared. In JavaScript, they exist in the complete (innermost) surrounding function:
function func(x) { console.log(tmp); // undefined if (x < 0) { var tmp = 100 - x; // (*) ... } }The cause of the above behavior is hoisting: Internally, the declaration at (*) is moved to the beginning of the function (the assignment stays where it is). That is, what a JavaScript engine actually executes looks like this:
function func(x) { var tmp; console.log(tmp); // undefined if (x < 0) { tmp = 100 - x; ... } }But there is a trick to limit the scope of a variable to a block, it is called Immediately Invoked Function Expression (IIFE, pronounced “iffy”). Below, we use an IIFE to restrict the scope oftmp to the then-block of the if statement.
function func(x) { console.log(tmp); // ReferenceError: tmp is not defined if (x < 0) { (function () { // open IIFE var tmp = 100 - x; ... }()); // close IIFE } }We wrapped a function around the insides of the block, creating a new scope for them. Then we immediately called that function.tmp only exists inside the IIFE. Note that the parentheses at the beginning and the end of the IIFE are necessary. They lead to the function being interpreted as an expression, which is the only form in which it can be be immediately invoked.
- JavaScript quirk 6: the scope of variables
- JavaScript quirk 7: inadvertent sharing of variables via closures
- JavaScript quirk 4: unknown variable names create global variables
- the variables of python
- The C programming Language -1.10 External Variables and Scope
- The scope of software engineering
- JavaScript quirk 5: parameter handling
- Scope Is the Enemy of Success
- JavaScript Variables
- JavaScript quirk 8: array-like objects
- The origin of "Hungarian" notation for naming variables
- VS2010 can not watch the value of local variables
- svn: None of the environment variables SVN_EDITOR...问题解决
- [CF 279D]The Minimum Number of Variables[状压dp]
- cf-279D - The Minimum Number of Variables-数位dp
- the thinker of code complete -- general issues in using variables
- svn: None of the environment variables SVN_EDITOR...问题解决
- the future of JavaScript
- ACCESS高效分页
- C++高级机制-异常
- Object类equals()
- CKEditor二次开发-替CKEditor增加添加水印的功能
- Oracle创建删除用户、角色、表空间、导入导出数据库命令行方式总结
- JavaScript quirk 6: the scope of variables
- CKEditor二次开发-为CKEditor增加下传图片的功能
- webkit 扩展 JavaScript 对象
- River Crossing nyoj716
- 颜色渐变
- 利用百度"喜欢"按钮一个账户变通成可以达到顶与踩功能的插件
- 导出 Excel
- ckeditor 配备
- c# Excel模板控制 自动换行