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

Groovy:封闭中的’this’的含义

发布时间:2020-12-14 16:30:58 所属栏目:大数据 来源:网络整理
导读:以下示例改编自“Groovy in Action” class Mother { Closure birth() { def closure = { caller - [this,caller] } return closure }} Mother julia = new Mother()closure = julia.birth() context = closure.call(this) println context[0].class.name //
以下示例改编自“Groovy in Action”

class Mother {

    Closure birth() {                            
        def closure = { caller ->
            [this,caller]
        }
        return closure
    }
}                    

Mother julia = new Mother()
closure = julia.birth()                                
context = closure.call(this)                             

println context[0].class.name        // Will print the name of the Script class
assert context[1] instanceof Script

根据这本书,封闭内部的价值是最外面的范围(即宣布朱利亚的范围).我正确地假设

>这个内部的一个闭包可以评估到关闭的范围吗?
>在上面所示的关闭中,这个和调用者是否参考相同的范围?

谢谢,

解决方法

看看第144页

…this refers to the closure,not to
the declaring object. At this point,
closures play a trick for us. They
delegate all method calls to a
so-called delegate object,which by
default happends to be the declaring
object (that is,the owner). This make
the closure appear as if the enclosed
code runs in the birthday context.

对于你的问题

this inside a closure evaluates to the scope in which the closure is called?

从书中他们说“这是指封闭,而不是声明对象”
但是从bertport和我的实验看,“这”实际上是声明对象.

无论哪种方式,您的问题的答案仍然是“否”.

within the closure shown above,this and caller refer to the same scope?

恐怕不是.

请注意,Groovy in Action中的第143和144页需要进行一些更正

http://groovy.canoo.com/errata/erratum/show/5

http://groovy.canoo.com/errata/erratum/show/8

(编辑:李大同)

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

    推荐文章
      热点阅读