了解 R 的范围界定演示

Understanding R's scoping demo

我尝试了解 R 中的范围演示,您可以通过 demo(scoping) 访问。

我不明白 total 变量保存在哪里。首先我认为根据 help("<<-")

The operators <<- and ->> are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment.

它在 global environment。但是因为我在那里找不到它 (ls(environment)) 我猜想 open.account <- function(total) 为由 open.account() 赋值创建的所有实例创建了一个总变量。但是如果我创建一个实例 ross <- open.account(100) 我找不到变量。

ross
...
<environment: 0x0000000011fbe998>

ls(environment(environment: 0x0000000011fbe998))getAnywhere(total) 的结果是 no object named ‘total’ was found。那么 total 的不同版本在哪里?

ross列表中的函数是闭包,即functions with data。 (从技术上讲,R 中的大多数函数都是闭包。但通常您不会关心它。)

所有这些闭包都是在对 open.account 的调用中定义的,因此它们与相同的环境相关联 "which provides the enclosure of the evaluation frame when the closure is used"(参见 help("closure"))。

total 在此环境中定义。

ross <- open.account(100)

environment(ross$deposit)
#<environment: 0x000000000ae10db8>
environment(ross$withdraw)
#<environment: 0x000000000ae10db8>
environment(ross$balance)
#<environment: 0x000000000ae10db8>

environment(ross$deposit)$total
#[1] 100