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

时间:2014-05-03 20:19:37

标签: 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()

输出

prop1
prop1
prop1

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

2 个答案:

答案 0 :(得分: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()

脚本的最后3行显示了如何更改默认委托并将其设置为闭包的示例。上次调用closure会在prop1#3

PROPERTY FROM SCRIPT脚本中打印println

答案 1 :(得分:6)

确定答案是,default所有者等于this,默认情况下delegate等于owner。因此,默认情况下delegate等于this。除非您更改delegate的设置,否则您将获得与this

相同的值