:( 什么是闭包?
闭包并非什么新奇的概念,它早在高级语言开始发展的年代就产生了。闭包(Closure)是词法闭包(Lexical Closure)的简称。对闭包的具体定义有不少种说法,这些说法大致能够分为两类:
一种说法认为闭包是符合必定条件的函数,好比参考资源中这样定义闭包:闭包是在其词法上下文中引用了自由变量(注 1)的函数。
另外一种说法认为闭包是由函数和与其相关的引用环境组合而成的实体。好比参考资源中就有这样的的定义:在实现深约束(注 2)时,须要建立一个能显式表示引用环境的东西,并将它与相关的子程序捆绑在一块儿,这样捆绑起来的总体被称为闭包。javascript
#python 中的闭包 ... def func(data): ... count = [data] ... def wrap(): ... count[0] += 1 ... return count[0] ... return wrap ... ... a = func(1) >>> a() 5: 2 >>> a() 6: 3 def func(x): ... return lambda y :y+x >>> b = func(1) >>> b(1) 7: 2 >>> b(2) 8: 3 >>> print b #这里b是个function 在ruby中是proc <function <lambda> at 0x01AC68F0> def addx(x): ... def adder (y): return x + y ... return adder >>> add8 = addx(8) >>> add8(8) 9: 16
#ruby 中的闭包 # Creates a new <code>Proc</code> object, bound to the current # context. <code>Proc::new</code> may be called without a block only # within a method with an attached block, in which case that block is # converted to the <code>Proc</code> object. # sum = 0 10.times{|n| sum += n} print sum def upto(from,to) while from <= to yield from from+=1 end end upto(1,10) {|n| puts n} def counter() i = 1 Proc.new{ puts i;i+=1} end c = counter() c.call() 1 c.call() 2
/*javascript中的闭包*/ function f1(){ n=999; function f2(){ alert(n); } return f2; } var result=f1(); result(); // 999 //用途 setInterval 传参数 function do_load_stock(market,code) { return function(){load_stock(market,code)}; } function time_loader(market,code) { var stock = market+code; if(CheckStockTime(stock)) { setInterval(do_load_stock(market,code),30000); } }