zoukankan      html  css  js  c++  java
  • Closure

    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 }

      

      This technique is often used in the global scope outside of functions to limit the number of variables and functions added to the global scope. Private scopes allow every developer to use his or her own variables without worrying about polluting the global scope.

  • 相关阅读:
    UIView的clipsToBounds属性,layoutSubViews及触摸事件传递(默认情况下)总结
    ISO中运行时简单使用及KVC补充
    IOS中UISearchBar的使用
    oc的block
    oc的协议(protocol)
    oc的分类category
    oc内存的理解
    oc笔记(转载)
    oc对象中属性总结
    servlet,struts1,struts2,spring
  • 原文地址:https://www.cnblogs.com/linxd/p/4509319.html
Copyright © 2011-2022 走看看