0

I'm going through the following S3-Tutorial: http://www.cyclismo.org/tutorial/R/s3Classes.html

I like the "Local Environment Approach" (and can live with its disadvantages). But I d'ont understand why there is the manual creation of a local environment. Why don't we just use the functions environment?

The following seems to workeven without the "extra" environment:

Person <- function(name) {

  name <- name

  me <- list(

    getName = function() {
      return(name)
    }    
  )


  class(me) <- append(class(me), "Person")
  return(me)
}

jan <- Person("Jan")
max <- Person("Max")

jan$getName()
max$getName()

What am I missing here?

Fabian Gehring
  • 1,133
  • 9
  • 24
  • 1
    You should try to add the `setName` method. But even so, you can use the `<<-` assignment operator ( `setName = function(x) { name <<- x }`) and don't have to store the environment explicitly in the list. – bergant Jun 10 '15 at 10:37
  • I see, is there a disadvantage of using <<- instead of the explicitly stored environment (code is much cleaner without, but are there speed or other drawbacks?). Is the use of <<- recommended in s3 classes? – Fabian Gehring Jun 10 '15 at 11:37
  • With `<<-` There is additional step to look up the parent environment, but I don't see any big advantage in using `assign` in this case. – bergant Jun 10 '15 at 12:31

0 Answers0