原来JavaScript的闭包概念是这样的
原来以为闭包是和内部函数有关系,这几天又重新看了JavaScript The Definitive Guide 5th.Edition,发现
8.8. Function Scope and Closures里是这么定义闭包的:
引用
JavaScript functions are a combination of code to be executed and the scope in which to execute them. This combination of code and scope is known as a closure in the computer science literature. All JavaScript functions are closures. These closures are only interesting, however, in the case discussed above: when a nested function is exported outside the scope in which it is defined. When a nested function is used in this way, it is often explicitly called a closure.
所以闭包其实就是一堆代码和某个scope组成的集合。我想称它为闭包的原因是因为在一个scope下的代码的执行都是封闭的(也就是说如果在不同的scope下执行相同的代码结果是不一样),不知道这样理解有没有问题。希望抛砖引玉了。