[Groovy] 请教groovy 中的delegate 和 this 及owner的关系

dellsoft 2007-10-13
如题,有人能解释一下三者的关系吗?
官方文档上有个代码?
class Class1 {
  def closure = {
    println this.class.name
    println delegate.class.name
    def nestedClos = {
      println owner.class.name
    }
    nestedClos()
  }
}

def clos = new Class1().closure
clos.delegate = this
clos()
/*  prints:
Class1
Script1
Class1$_closure1  */

希望能解释一下啊
agile_boy 2007-10-23
this, owner, and delegate

this : as in Java, this refers to the enclosing class where a Closure is defined
owner : the enclosing object (this or a surrounding closure)
delegate : by default the same as owner, but changeable for example in a builder or ExpandoMetaClass

上面是官方的说明,我的理解是:
this根java差不多,不需要多做说明。
owner是当前代码块属于谁的,示例就是很好的说明。
delegate默认跟owner相同,但是可以被改变,有了delegate可以让closure更灵活,比如可以设置owner以外的properties。
Global site tag (gtag.js) - Google Analytics