【问题标题】:this, owner, delegate in Groovy closure这个,所有者,Groovy 闭包中的委托
【发布时间】:2014-06-20 09:23:45
【问题描述】:

这是我的代码:

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。他们为什么不呢?

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    这就是它的工作原理。您必须了解owner和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 SCRIPTprintln #3

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-29
        • 1970-01-01
        • 2019-10-08
        • 2019-06-23
        • 2013-07-07
        • 1970-01-01
        • 1970-01-01
        • 2013-07-14
        相关资源
        最近更新 更多