Skip to content
Prev 206691 / 398506 Next

Can an object reference itself?

Hadley,

thanks for your comment. What you're saying is true, of course, and possibly
I did not really chose the best header to describe the actual issue I was
addressing. However, in the help archive I found something that gets me what
I want (calling a certain "slot function" without having to specify
arguments at calling time). I adapted it to my situation and maybe it's of
interest for someone facing a similar problem.

setClass(
	Class="Testclass",
	representation=representation(
		env="environment",
		data="function"
	)
)

data.fun <- function(env) get("actual.data", env=env)

setMethod(
	f="initialize", 
	signature=signature("Testclass"), 
	definition=function(
		.Object, 
		actual.data=NULL, 
		...
	) {
	     env 			<- new.env(parent=emptyenv())
	     env$actual.data 	<- actual.data
		 
		data.fun.wrapper <- function() data.fun(env)
		 
	     callNextMethod(.Object, env=env, data=data.fun.wrapper, ...)
 	}
)

obj <- new("Testclass", actual.data=1:10)
obj at data()
obj at env$actual.data	<- 1:5
obj at data()

obj.mod <- new("Testclass")
obj.mod at env$actual.data	<- "horst"
obj.mod at data()

Loading an object from harddrive could be implemented in a similar way by
putting the path-filename-combination in "obj at env" and adapting the function
"data.fun()" accordingly.

Putting "data.fun()" into the wrapper "data.fun.wrapper()" allows for
changes in "data.fun()" without having to re-source the method for
"initialize()" and to reassign "obj" each time.

Regards,
Janko