加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy中Closure的this到底指向谁?

发布时间:2020-12-14 16:52:25 所属栏目:大数据 来源:网络整理
导读:Groovy in?Action(中文版)第136页明确说Closure的this指向Closure自己。并且从代码注释处作者也是这样理解的: class Mother{ ??? int field = 1 ??? int foo(){ ??????? return 2 ??? } ??? Closure birth(param){ ??????? def local = 3 ??????? def closu

Groovy in?Action(中文版)第136页明确说Closure的this指向Closure自己。并且从代码注释处作者也是这样理解的:

class Mother{
??? int field = 1
??? int foo(){
??????? return 2
??? }

??? Closure birth(param){
??????? def local = 3
??????? def closure = { caller->
??????????? [
??????????????? this,
??????????????? field,
??????????????? foo(),
??????????????? local,
??????????????? param,
??????????????? caller,
??????????????? this.owner
??????????? ]
??????? }
??????? return closure
??? }
}

Mother julia? = new Mother()

closure = julia.birth(4)
context = closure.call(this)
println context[0].class.name??????????? //(4) Script

............................................

assert context[6] instanceof Mother //作者认为this指向自己,所以this.owner指向Mother


但是,上面的代码实际是错误的,我用1.0和2.1分别运行,都是一样的结果。this,也就是context[0]是Mother的this,而不是Closeure的。并且this.owner报错,提示Mother找不到属性owner.

其实Closure中引用this是它所在的上下文的this.对于上例其实就是Mother.this,是closure的owner,这也是Closure的delegate的默认值.要想在Closure是引用自己,只有引用delegate,然后在外部调用时将closure的delegate指向自己:

class Mother{??? int field = 1??? int foo(){??????? return 2??? }??? Closure birth(param){??????? def local = 3??????? def closure = { caller->??????????? [??????????????? delegate,??????????????? field,??????????????? this.foo(),??????????????? local,??????????????? param,??????????????? caller,??????????????? delegate.owner??????????? ]??????? }??????? return closure??? }}Mother julia? = new Mother()closure = julia.birth(4)closure.delegate = closurecontext = closure.call(this)println context[0].class.name

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读