[转]What is closure

what is closure?

-- A closure is a function that can access interesting non-local variables

Variable scope

When you declare a local variable, that variable has a scope. Generally local variables exist only within the block or function in which you declare them.

function() {
  var a = 1;
  console.log(a); // works
}
console.log(a); // fails

If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.

var a = 1;
function() {
  console.log(a); // works
}
console.log(a); // works

When a block or function is done with, its local variables are no longer needed and are usually blown out of memory.

This is how we normally expect things to work.

A closure is a persistent local variable scope

A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere.

The scope object, and all its local variables, are tied to the function, and will persist as long as that function persists.

This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context.

For example

Here‘s a really simple example in JavaScript that illustrates the point:

outer = function() {
  var a = 1;
  var inner = function() {
    alert(a);
  }
  return inner; // this returns a function
}

var fnc = outer(); // execute outer to get inner
fnc();

Here I have defined a function within a function. The inner function gains access to all the outer function‘s local variables, including a. The variable a is in scope for the inner function.

Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc, so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist. The variable a has been closed over -- it is within a closure.

Note that the variable a is totally private to fnc. This is a way of creating private variables in a functional programming language such as JavaScript.

As you might be able to guess, when I call fnc() it alerts the value of a, which is "1".

In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists.

In JavaScript, the variable a persists because variable scope is created when the function is first declared, and persists for as long as the function continues to exist.

a belongs to the scope of outer. The scope of inner has a parent pointer to the scope of outerfnc is a variable which points to innera persists as long as fnc persists. a is within the closure.

时间: 2024-10-07 23:37:26

[转]What is closure的相关文章

学习Javascript闭包(Closure)

闭包(closure)是Javascript语言的一个难点,也是它的特色,很多高级应用都要依靠闭包实现. 下面就是我的学习笔记,对于Javascript初学者应该是很有用的. 一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变量. Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量. var n=999; function f1(){ alert(n); } f1(); // 999 另一方面,在函数外

聊一下JS中的作用域scope和闭包closure

scope和closure是javascript中两个非常关键的概念,前者JS用多了还比较好理解,closure就不一样了.我就被这个概念困扰了很久,无论看别人如何解释,就是不通.不过理越辩越明,代码写的多了,小程序测试的多了,再回过头看看别人写的帖子,也就渐渐明白了闭包的含义了.咱不是啥大牛,所以不搞的那么专业了,唯一的想法就是试图让你明白什么是作用域,什么是闭包.如果看了这个帖子你还不明白,那么多写个把月代码回过头再看,相信你一定会有收获:如果看这个帖子让你收获到了一些东西,告诉我,还是非常

javascript Closure 闭包

引用自 http://www.cnblogs.com/mguo/archive/2013/06/19/3143880.html /*一.变量的作用域要理解闭包,首先必须理解Javascript特殊的变量作用域.变量的作用域无非就是两种:全局变量和局部变量.Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量.*/ var n=999; function f1(){ alert(n); } f1(); // 999//另一方面,在函数外部自然无法读取函数内的局部变量. funct

Swift闭包(Closure)

语法: { (parameters) ->return type in statements} 实例:采用函数实现: let names =["Chris", "Alex", "Ewa", "Barry", "Daniella"] funcbackwards(s1: String, s2: String) -> Bool { return s1 > s2 } var reversed =

Swift 闭包(closure)

Swift中的闭包,就是Objective-C中的Block, 其实两者是一个东西 1.Closure变量的声明 (1)Closure就是匿名函数,我们可以定义一个闭包变量,而这个闭包变量的类型就是我们上面介绍的“函数类型”. 定义一个闭包变量其实就是定义一个特定函数类型的变量,方式如下. 因为Closure变量没有赋初始值,所以我们把其声明为可选类型的变量.在使用时,用!强制打开即可. var myCloure0:((Int, Int) -> Int)? (2)我们还用另一种常用的声明闭包变量

python 闭包(closure)

闭包的定义: 闭包就是一个函数,这个函数可以记住封闭作用域里的值,而不管封闭作用域是否还在内存中. 来一个例子: def happy_add(a): print 'id(a): %x' % id(a) def do_add(b): return a + b print 'id(do_add): %x' % id(do_add) return do_add test_one = happy_add(1) test_one(9) print repr(test_one) print '\n-----

Apache Commons Collections基本操作(Predicate、Transformat、Closure等)

一.Predicate断言 package Collections; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.functors.EqualPredic

javascript 闭包(closure)

<script type="text/javascript">    //闭包(closure):内层函数可以引用存在于包围它的函数内的变量,即使外层函数的执行已经结束    //注意内层函数引用的外层函数内的变量是外层函数执行结束后的最终值    test(1);    function test(a) { //外层函数        alert(a+' 外层函数开始执行');        setTimeout(function(){//内层函数           

Swift语言精要-闭包(Closure)

闭包(Closure)这个概念如果没学过Swift的人应该也不会陌生. 学过Javascript的朋友应该知道,在Javascript中我们经常会讨论闭包,很多前端工程师的面试题也会问到什么是闭包. 那么,什么是闭包呢? 让我们看下在Javascript中闭包的解释: Closures are functions that have access to variables from another function’s scope. (This is often accomplished by

JavaScript 的closure 和 hoisting

闭包(closure) 当声明一个函数时,其内部的变量的声明也在它的scope中被截获.比如下面的代码中,变量 x 绑定到了外部scope的值,然后对 x 的引用在bar的上下文中被截获. var x = 4; // declaration in outer scope function bar() { console.log(x); // outer scope is captured on declaration } bar(); // prints 4 to console "截获&quo