且构网

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

相当于 R 中的“this"或“self"

更新时间:2022-04-17 05:35:33

引用类 (RC) 对象基本上是封装环境的 S4 对象.环境持有 RC 对象的字段,并被设置为其方法的封闭环境;这就是对字段标识符的非限定引用绑定到实例字段的方式.我能够在环境中找到一个 .self 对象,我认为这正是您正在寻找的对象.

Reference class (RC) objects are basically S4 objects that wrap an environment. The environment holds the fields of the RC object, and is set as the enclosing environment of its methods; that's how unqualified references to the field identifiers bind to the instance's fields. I was able to find a .self object sitting in the environment that I believe is exactly what you're looking for.

x <- MyObject$new(); ## make a new RC object from the generator
x; ## how the RC object prints itself
## Reference class object of class "MyObject"
## Field "name":
## character(0)
## Field "age":
## numeric(0)
is(x,'refClass'); ## it's an RC object
## [1] TRUE
isS4(x); ## it's also an S4 object; the RC OOP system is built on top of S4
## [1] TRUE
slotNames(x); ## only one S4 slot
## [1] ".xData"
x@.xData; ## it's an environment
## <environment: 0x602c0e3b0>
environment(x$getPrinter); ## the RC object environment is set as the closure of its methods
## <environment: 0x602c0e3b0>
ls(x@.xData,all.names=T); ## list its names; require all.names=T to get dot-prefixed names
## [1] ".->age"       ".->name"      ".refClassDef" ".self"        "age"          "field"
## [7] "getClass"     "name"         "show"
x@.xData$.self; ## .self pseudo-field points back to the self object
## Reference class object of class "MyObject"
## Field "name":
## character(0)
## Field "age":
## numeric(0)

所以解决方案是:

MyObject <- setRefClass("MyObject",
    fields = list(name = "character", age = "numeric"),
    methods = list(
        getPrinter = function() {
            MyPrinter$new(obj=.self)
        }
    )
)