First they ignore you
then they ridicule you
then they fight you
then you win
    -- Mahatma Gandhi
Chinese => English     英文 => 中文             
随笔-221  评论-1047  文章-0  trackbacks-0
在上篇《Groovy解惑——closure中的delegate》中,我帮大家讲解了delegate是什么以及其作用。
本篇将讲解一下closure中的owner,以及this,delegate以及owner三者间的关系。

先让我们来看个例子:
class OwnerDemo {
    def outerClosure 
= {
        println 
"the owner of outerClosure: " + owner

        def innerClosure 
= { 
            println 
"the owner of innerClosure: " + owner 

            def innestClosure 
= {
                println 
"the owner of innestClosure: " + owner
            }
            innestClosure()
        }
        innerClosure()
    }
}

def ownerDemo 
= new OwnerDemo()
ownerDemo.outerClosure()
运行结果:
the owner of outerClosure: OwnerDemo@eccfe7
the owner of innerClosure: OwnerDemo$_closure1@4745cf
the owner of innestClosure: OwnerDemo$_closure1_closure2@109dcbb
注意:OwnerDemo$_closure1指的是outerClosure的类名,而OwnerDemo$_closure1_closure2指的是innerClosure的类名
通过这个例子,大家就清楚了,closure的owner引用的是该closure的‘拥有者’

那么this, delegate以及owner有什么关系呢?
隐式变量delegate的默认值为owner,
如果closure没有‘嵌套’在其他closure中,那么该closure的owner的值为this;
否则该closure的owner引用的是‘直接包含’该closure的closure


让我们用事实来说话吧:
class OwnerDemo {
    def outerClosure 
= {
        println 
"the owner of outerClosure: " + owner
        println 
"the delegate of outerClosure: " + delegate
        println 
"this in the outerClosure: " + this
        def innerClosure 
= { 
            println 
"the owner of innerClosure: " + owner 
            println 
"the delegate of innerClosure: " + delegate 
            println 
"this in the innerClosure: " + this 
            def innestClosure 
= {
                println 
"the owner of innestClosure: " + owner
                println 
"the delegate of innestClosure: " + delegate
                println 
"this in the innestClosure: " + this
            }
            println 
"innestClosure: " + innestClosure
            innestClosure()
        }
        println 
"innerClosure: " + innerClosure
        innerClosure()
    }
}

def ownerDemo 
= new OwnerDemo()
def outerClosure 
= ownerDemo.outerClosure
println 
"outerClosure: " + outerClosure
outerClosure()
运行结果:
outerClosure: OwnerDemo$_closure1@10cc9b4
the owner of outerClosure: OwnerDemo@8e7f54
the delegate of outerClosure: OwnerDemo@8e7f54
this in the outerClosure: OwnerDemo@8e7f54
innerClosure: OwnerDemo$_closure1_closure2@1eb1db2
the owner of innerClosure: OwnerDemo$_closure1@10cc9b4
the delegate of innerClosure: OwnerDemo$_closure1@10cc9b4
this in the innerClosure: OwnerDemo@8e7f54
innestClosure: OwnerDemo$_closure1_closure2_closure3@12a78ee
the owner of innestClosure: OwnerDemo$_closure1_closure2@1eb1db2
the delegate of innestClosure: OwnerDemo$_closure1_closure2@1eb1db2
this in the innestClosure: OwnerDemo@8e7f54

大家可以从其中值的关系看出this, delegate以及owner三者的关系与我们之前所说的相符 :)

连夜连发2篇文章以回报‘蛟龙居’的常客 :)

附:朝花夕拾——Groovy & Grails


posted on 2007-12-23 01:43 山风小子 阅读(2976) 评论(3)  编辑  收藏 所属分类: Groovy & Grails