且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

'closures'的定义

更新时间:2023-10-29 23:09:16

从技术上讲,所有函数都是闭包。但是如果函数不引用任何***变量,闭包的环境是空的。函数和闭包之间的区别只有在需要与函数代码一起保存的闭合变量时才感兴趣。因此,通常将不访问任何***变量的函数称为函数和那些作为闭包的函数,以便了解这种区别。


Let me ask one question. It's about closures in JavaScript, but not about how they work.

David Flanagan in his "JavaScript The Definitive Guide 6th Edition" wrote:

...Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them....

Is this correct? Can I call every function (function object + it's scope) a "closure"?

And stacks' tag "closures" says:

A closure is a first-class function that refers to (closes over) variables from the scope in which it was defined. If the closure still exists after its defining scope ends, the variables it closes over will continue to exist as well.

In JavaScript every function refers to variables from the scope in which it was defined. So, It's still valid.

The question is: why do so many developers think otherwise? Is there something wrong with this theory? Can't it be used as general definition?

Technically, all functions are closures. But if the function doesn't reference any free variables, the environment of the closure is empty. The distinction between function and closure is only interesting if there are closed variables that need to be saved along with the function code. So it's common to refer to functions that don't access any free variables as functions, and those that do as closures, so that you know about this distinction.