zoukankan      html  css  js  c++  java
  • 介绍 JavaScript 中的闭包、局部变量(局部作用域)和私有变量等内容

    .闭包

      
    JavaScript中的闭包,是指一个函数可以访问另一个函数作用域中
    的变量。这通常通过将一个函数定义在另一个函数内部来完成。如:

         
    functioncreateComparisonFunction(propertyName)
         
    {
            
    returnfunction(object1,object2)
            
    {
               
    varvalue1=object1[propertyName];//访问外部函数变量
                varvalue2=object2[propertyName];
               
    if(value1<value2)
               
    {
                  
    return-1;
               
    }elseif(value1>value2)
               
    {
                  
    return1;
               
    }else
               
    {
                  
    return0;
               
    }
            
    };
         
    }
         
    //create function
          varcompareNames=createComparisonFunction("name");
         
    //call function
          varresult=compareNames({name:"Nicholas"},{name:"Greg"});
         
    //dereference function - memory can now be reclaimed
          compareNames=null;

      
    闭包会引用外部函数作用域,会占用更多的内存,过度使用闭包,
    会导致性能问题。所以,仅当必要时才使用闭包。对产生闭包的函数,
    使用后应该解除引用。

  • 相关阅读:
    洛谷—— P2234 [HNOI2002]营业额统计
    BZOJ——3555: [Ctsc2014]企鹅QQ
    CodeVs——T 4919 线段树练习4
    python(35)- 异常处理
    August 29th 2016 Week 36th Monday
    August 28th 2016 Week 36th Sunday
    August 27th 2016 Week 35th Saturday
    August 26th 2016 Week 35th Friday
    August 25th 2016 Week 35th Thursday
    August 24th 2016 Week 35th Wednesday
  • 原文地址:https://www.cnblogs.com/shn1637/p/3456602.html
Copyright © 2011-2022 走看看