S3 泛型中的变量范围

Variable scope in S3 generics

我有以下片段:

y <- 1
g <- function(x) {
  y <- 2
  UseMethod("g")
}
g.numeric <- function(x) y
g(10)
# [1] 2

我不明白,为什么可以在 g.numeric <- function(x) y 中访问 y。据我了解,y 的范围仅在泛型 (g <- ...) 的定义范围内。谁能给我解释一下,这怎么可能?

可以在?UseMethod帮助页面

中找到关于此行为的描述

UseMethod creates a new function call with arguments matched as they came in to the generic. Any local variables defined before the call to UseMethod are retained

因此,函数调用 UseMethod 中定义的任何局部变量都作为局部变量传递给下一个函数。你可以用

看到这个
g.numeric <- function(x) ls()  #lists all variables in current environment
g(10)
# [1] "x" "y"
g.numeric(10)
# [1] "x"