簡體   English   中英

這個,所有者,Groovy關閉委托

[英]this, owner, delegate in Groovy closure

這是我的代碼:

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。 為什么不是他們?

這是它的工作原理。 您必須了解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將打印來自println #3的PROPERTY FROM SCRIPT腳本的prop1

好的答案是, default所有者等this ,默認delegate等於owner 因此,默認delegatethis 當然,除非你改變的設置delegate ,你因此得到同等價值,你會從this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM