Groovy 闭包中的 this、owner、delegate

2024-04-03

这是我的代码:

class SpecialMeanings{
  String prop1 = "prop1"
  def closure = {
    String prop1 = "inner_prop1"  
    println this.class.name //Prints the class name
    println this.prop1
    println owner.prop1
    println delegate.prop1
  }
}

def closure = new SpecialMeanings().closure
closure()

输出是

prop1
prop1
prop1

我希望第一行是 prop1,因为它指的是定义闭包的对象。但是,所有者(并且是默认委托)应该引用实际的闭包。所以接下来的两行应该是inner_prop1。为什么不是?


这就是它的工作原理。你必须了解的实际参考owner and delegate. :)

class SpecialMeanings{
  String prop1 = "prop1"
  def closure = {
    String prop1 = "inner_prop1"  
    println this.class.name //Prints the class name

    //Refers to SpecialMeanings instance
    println this.prop1 // 1

    // owner indicates Owner of the surrounding closure which is SpecialMeaning
    println owner.prop1 // 2

    // delegate indicates the object on which the closure is invoked 
    // here Delegate of closure is SpecialMeaning
    println delegate.prop1 // 3

    // This is where prop1 from the closure itself in referred
    println prop1 // 4
  }
}

def closure = new SpecialMeanings().closure
closure()

//Example of modifying the delegate to the script itself
prop1 = "PROPERTY FROM SCRIPT"
closure.delegate = this
closure()

脚本的最后 3 行显示了如何更改默认委托并将其设置为闭包的示例。最后一次调用closure会打印prop1脚本中的值是PROPERTY FROM SCRIPT at println # 3

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Groovy 闭包中的 this、owner、delegate 的相关文章

随机推荐