这个,所有者,Groovy关闭委托

Mor*_*ive 3 groovy closures

这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

输出是

prop1
prop1
prop1
Run Code Online (Sandbox Code Playgroud)

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

dma*_*tro 10

这是它的工作原理.你必须了解的实际参考ownerdelegate.:)

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()
Run Code Online (Sandbox Code Playgroud)

最后3行脚本显示了如何更改默认委托并将其设置为闭包的示例.最后调用closure将打印prop1从作为脚本值PROPERTY FROM SCRIPTprintln#3


Mor*_*ive 6

好的答案是,default所有者等于this,默认情况下delegate等于owner.因此,默认delegate等于this.除非您更改设置,否则delegate您将获得与之相同的值this