首页 > 其他 > 详细

Closure - Mimicking block scope

时间:2015-05-17 11:58:50      阅读:206      评论:0      收藏:0      [点我收藏+]

The basic syntax of an anoymous function used as a block scope (often called a private scope) is as follows:

(function(){

  // block code here

}) ();

A variable is just a representation of another value, so the variable can be replaced with the actual value, and the code works fine.

var someFunction = function(){

  // block code here

};

somefunction();

However, the following won‘t work:

function(){

  // block code here

}();        // error

The code causes a syntax error, because JavaScript sees the function keyword as the begining of a function declaration, and function declarations cannot be followed by parentheses. Function expressions, however, can be followed by parentheses. To turn the function declaration into a function expression, you need only surround it with the parentheses like this:

(function(){

  //block code here 

})();

These private scopes can be used anywhere variables are needed temporarily, as in this example:

1 function outputNumbers(count){
2     (function(){
3         for (var i=0; i<count; i++){
4             alert(i);
5         }
6     }) ();
7   
8     alert(i);           // causes an error   
9 }

 

Closure - Mimicking block scope

原文:http://www.cnblogs.com/linxd/p/4509319.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!