'closures'的定义 [英] Definition of 'closures'

查看:93
本文介绍了'closures'的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我问一个问题。



David Flanagan在他的JavaScript The Definitive Guide 6th Edition中写道:



... 技术上来说,所有的JavaScript函数都是闭包:它们是对象,它们有一个范围链与它们相关联。 ... / p>

这样是否正确?我可以调用每个函数(函数对象+它的范围)一个闭包?



和stacks'标签闭包说:



闭包是一个第一类函数,它引用(关闭)来自定义范围的变量。如果闭包在定义范围之后仍然存在



在JavaScript中,每个函数都引用来自定义的范围的变量。

问题是: 为什么这么多开发者会这样想呢?这个理论有什么问题吗?

解决方案

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


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.

这篇关于'closures'的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆