Groovy闭包中的这个、所有者、委托
这是我的密码:Groovy闭包中的这个、所有者、委托,groovy,closures,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 clos
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,因为它引用了定义闭包的对象。但是,所有者(并且是默认的委托人)应该引用实际的闭包。所以接下来的两行应该是内部的。为什么没有呢?这就是它的工作原理。您必须了解
所有者
和代表
的实际参考:
脚本的最后3行显示了如何更改默认委托并将其设置为闭包的示例。最后一次调用
closure
将打印脚本中的prop1
值,该值是println
#3处脚本的prop1
属性,答案是默认情况下所有者等于此
,默认情况下委托等于所有者
。因此,默认情况下,委托
等于此
。当然,除非您更改委托
的设置,否则您将获得与此
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()