In groovy, who is the point of closure's this?

Source: Internet
Author: User

Groovy in Action (Chinese version) page 136th clearly states that this of closure points to closure itself. The author also understands this from the code comment:

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 // The author thinks this points to himself, so this. Owner points to mother

However, the above Code is actually incorrect. I run the Code with 1.0 and 2.1 respectively, and the results are the same. This, that is, context [0] is mother's this, rather than closeure. And this. Owner reports an error, prompting that the property owner cannot be found by mother.

In fact, closure references this as the context of this. For the above example, it is actually mother. This, which is the owner of closure, which is also closure'sDelegateThe default value of closure. to reference closure, only delegate is referenced, and then the closure delegate points to itself during external calls:

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 = Closure
Context = closure. Call (this)
Println context [0]. Class. Name

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.