原来以为闭包是和内部函数有关系,这几天又重新看了JavaScript The Definitive Guide 5th.Edition,发现
8.8. Function Scope and Closures里是这么定义闭包的:
[quote]
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.
[/quote]
所以闭包其实就是一堆代码和某个scope组成的集合。我想称它为闭包的原因是因为在一个scope下的代码的执行都是封闭的(也就是说如果在不同的scope下执行相同的代码结果是不一样),不知道这样理解有没有问题。希望抛砖引玉了。
8.8. Function Scope and Closures里是这么定义闭包的:
[quote]
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.
[/quote]
所以闭包其实就是一堆代码和某个scope组成的集合。我想称它为闭包的原因是因为在一个scope下的代码的执行都是封闭的(也就是说如果在不同的scope下执行相同的代码结果是不一样),不知道这样理解有没有问题。希望抛砖引玉了。
本文通过《JavaScript The Definitive Guide 5th Edition》一书的内容,深入探讨了JavaScript中闭包的概念及其工作原理。作者指出,闭包实际上是由代码和特定的作用域组合而成的一个整体,并强调了当内部函数被外部作用域引用时,闭包的重要性。

被折叠的 条评论
为什么被折叠?



