本篇將講解一下closure中的owner以及thisdelegate以及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()
ownerDemoouterClosure()
運行結果
the owner of outerClosure: OwnerDemo@eccfe
the owner of innerClosure: OwnerDemo$_closure@cf
the owner of innestClosure: OwnerDemo$_closure_closure@dcbb
注意OwnerDemo$_closure指的是outerClosure的類名而OwnerDemo$_closure_closure指的是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 = ownerDemoouterClosure
println outerClosure: + outerClosure
outerClosure()
運行結果
outerClosure: OwnerDemo$_closure@ccb
the owner of outerClosure: OwnerDemo@ef
the delegate of outerClosure: OwnerDemo@ef
this in the outerClosure: OwnerDemo@ef
innerClosure: OwnerDemo$_closure_closure@ebdb
the owner of innerClosure: OwnerDemo$_closure@ccb
the delegate of innerClosure: OwnerDemo$_closure@ccb
this in the innerClosure: OwnerDemo@ef
innestClosure: OwnerDemo$_closure_closure_closure@aee
the owner of innestClosure: OwnerDemo$_closure_closure@ebdb
the delegate of innestClosure: OwnerDemo$_closure_closure@ebdb
this in the innestClosure: OwnerDemo@ef
大家可以從其中值的關系看出this delegate以及owner三者的關系與我們之前所說的相符 :)
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25968.html