views:

140

answers:

1

Hi,

In the following Groovy code snipped to add a fileAsString method to the String class, could someone explain what exactly 'this' refers to. I thought it was the object on which the fileAsString method is invoked, but apparently that's actually what delegate refers to.

String.metaClass.fileAsString = {
    this.class.getResourceAsStream(delegate).getText()
}

Thanks, Don

+2  A: 

The newly defined method is a closure, so 'this' will have the same meaning as it does when the method is defined. Usually 'this' will refer to the object that defined the method, like below:

class Foo {
    def meta() {
        String.metaClass.bar = {
            println(this.class)   // 'this' refers to the instance of Foo
        }
    }

    def main() {
        meta()
        new String().bar()
    }
}
new Foo().main()                  // prints "class Foo"
dbarker
What does 'this' refer to if the code does not appear within a class, e.g. in a script?
Don
Groovy generates a class from a script (the class will extend groovy.lang.Script). 'this' in a script refers to the instance of that generated class.
dbarker