zoukankan      html  css  js  c++  java
  • Closures

    Closures

      A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. Just like block in Objective-C.But Objective-C Block is more weird, cause Block contains a distinct terminology between copy & retain.

      Here's a slightly more interesting example — a makeAdder function:

    1. function makeAdder(x) {  
    2.   return function(y) {  
    3.     return x + y;  
    4.   };  
    5. }  
    6.   
    7. var add5 = makeAdder(5);  
    8. var add10 = makeAdder(10);  
    9.   
    10. print(add5(2));  // 7  
    11. print(add10(2)); // 12  

      In this example, we have defined a function makeAdder(x) which takes a single argument x and returns a new function. The function it returns takes a single argument y, and returns the sum of x and y.

      In essence, makeAdder is a function factory — it creates functions which can add a specific value to their argument. In the above example we use our function factory to create two new functions — one that adds 5 to its argument, and one that adds 10.

      add5 and add10 are both closures. They share the same function body definition, but store different environments. In add5's environment, x is 5. As far as add10 is concerned, x is 10.

     

      More information will be found here:https://developer.mozilla.org/en/JavaScript/Guide/Closures

  • 相关阅读:
    MSSQL如何将查询结果拼接成字符串
    SQL删除指定条件的重复数据,只保留一条
    清除日志
    jsp使用
    Eclipse使用
    SSM框架开发遇到的问题
    SpringMvc学习
    大中华~~汉字
    Word技巧设置
    AWS-资源访问慢分析
  • 原文地址:https://www.cnblogs.com/tekkaman/p/2577434.html
Copyright © 2011-2022 走看看