void main() {
A one = new A(1);
A two = new A(2);
var fnRef = one.getMyId; //A closure created here
var anotherFnRef = two.getMyId; //Another closure created here
}
class A{
int _id;
A(this._id);
int getMyId(){
return _id;
}
}
按照dart language tour頁面引用方法,這樣造成每次新的閉包。有誰知道它爲什麼這樣做?我可以理解在定義方法體時創建閉包,因爲我們可以在方法體中使用外部範圍中的變量,但是當引用上述方法時,爲什麼要創建閉包,因爲方法體不會更改,所以它不能使用該範圍內可用的任何變量可以嗎?我注意到在previous問題中,我問過像這樣的引用方法有效地將它們綁定到它們所引用的對象。所以在上面的例子中,如果我們調用fnRef()
它將表現得像one.getMyId()
那麼閉包只用於綁定調用上下文嗎? ......我很困惑:S爲什麼dart在引用方法時創建閉包?
UPDATE
針對Ladicek。那麼這是否意味着:
void main(){
var fnRef = useLotsOfMemory();
//did the closure created in the return statement close on just 'aVeryLargeObj'
//or did it close on all of the 'veryLargeObjects' thus keeping them all in memory
//at this point where they aren't needed
}
useLotsOfMemory(){
//create lots of 'veryLarge' objects
return aVeryLargeObj.doStuff;
}