什么是闭包?
闭包的设计思想?
实现闭包的方式?
被虐的体无完肤啊。。。。。。。。。。
闭包的英文:closure 或 lexical closure
百度百科:
闭包是指可以包含自由(未绑定到特定对象)变量的代码块;这些变量不是在这个代码块内或者任何全局上下文中定义的,而是在定义代码块的环境中定义(局部变量)。“闭包” 一词来源于以下两者的结合:要执行的代码块(由于自由变量被包含在代码块中,这些自由变量以及它们引用的对象没有被释放)和为自由变量提供绑定的计算环境(作用域)。在PHP、Scala、Scheme、Common Lisp、Smalltalk、Groovy、JavaScript、Ruby、 Python、Go、Lua、objective c、swift 以及Java(Java8及以上)等语言中都能找到对闭包不同程度的支持。
WIKI是这样描述的:
In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function together with an environment:
a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.
看个例子:
function startAt(x)
function incrementBy(y)
return x + y
return incrementBy
variable closure1 = startAt(1)
variable closure2 = startAt(5)
通俗点讲:
在函数startAt中内嵌了函数incrementBy,内嵌的函数incrementBy访问了x变量。之所以incrementBy可以访问x,就是因为incrementBy在x的闭包范围内, 尽管x对于incrementBy来说不是本地变量。
Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions ‘remember’ the environment in which they were created.
再看一个例子:
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
以上的代码都是js代码,也就是说虽然闭包不是最开始用在js中,但是人们所熟悉的闭包,就是在js中的应用。
接下来就要看看C++中的闭包:
We describe an extension of the C++ programming language that allows the nesting
of function definitions and provides lexical closures with dynamic lifetime.
c++11中引入的lambda可看作closure的一个实现,这里就不再赘述了,之前也写了很多文章关于lambda的使用问题。
#include <iostream>
#include <functional>
std::function<int()> make_my_closure(int x){
return [x]() mutable {
++x;
return x;
};
}
int main()
{
auto my_f = make_my_closure(10);
std::cout << my_f() << std::endl; // 11
std::cout << my_f() << std::endl; // 12
std::cout << my_f() << std::endl; // 13
auto my_f1 = make_my_closure(1);
std::cout << my_f1() << std::endl; // 2
std::cout << my_f1() << std::endl; // 3
std::cout << my_f1() << std::endl; // 4
}
参考:
http://www-cs-students.stanford.edu/~blynn//files/lexic.pdf
http://www.cprogramming.com/c++11/c++11-lambda-closures.html