这个,所有者,在Groovy闭包中的代表 [英] this, owner, delegate in Groovy closure

查看:62
本文介绍了这个,所有者,在Groovy闭包中的代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

  class SpecialMeanings {
字符串prop1 = prop1
def闭包= {
字符串prop1 = inner_prop1
println this.class.name //打印类名
println this.prop1
println owner.prop1
println proxy.prop1
}
}

def闭包= new SpecialMeanings()。closure
闭包()

输出为

  prop1 
prop1
prop1

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

解决方案

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

Here is my code:

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()

output is

prop1
prop1
prop1

I would expect the first line to be prop1 as this refers to the object in which the closure is defined. However, owner (and be default delegate) should refer to the actual closure. So the next two lines should have been inner_prop1. Why weren't they?

解决方案

OK the answer is that by default owner is equal to this and by default delegate is equal to owner. Therefore, by default delegate is equal to this. Unless of course you change the setting of delegate, you therefore get the equivalent value as you would from this

这篇关于这个,所有者,在Groovy闭包中的代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆