Re: [ js ] closure 與 garbage collection 問題?
我再說明清楚我的想法好了@@
※ 引述《B9 (葉酸酸)》之銘言:
: javascript:(function()
: {
在 scope chain 最前端加上一個 call object 1
: // outer. //
: var cat = (function()
call object 1 加入 cat 這個變數
: {
在 scope chain 最前端再加上一個 call object 2
: // inner. //
: var closure =
call object 2 加入 closure 這個變數。
: {
: height: 3
call object 2 的 closure 變數加上 height 這個 property。
: };
: var cat =
call object 2 加入 cat 這個變數。
: {
: age: function(age)
call object 2 的 cat 變數加上 age 這個 property。
age property 指向一個 anonymous function。
anonymous function 指向 call object 2 的 closure 變數的 property age。
: {
: if (!arguments.length)
: return closure.age;
: closure.age = age;
: return this;
: }
: };
將 call object 2 的 cat 變數回傳到 outer,並 assign 給
call object 1 的 cat 變數。
: return cat;
: })();
函數執行結束,開始對做 garbage collection。
call object 2 的可能性:
1. closure 在 anonymous function 中被 refer,所以不能被回收,
而 closure.height 跟 closure.age 都被 closure refer,所以不能回收,
最後 closure, closure.height, closure.age 都沒有被回收。
2. closure 在 anonymous function 中沒有被 refer,
因為 closure.age 回傳的時候被 dereferencing,
closure 沒有被 refer 所以被回收,closure 被回收,
表示 closure.height 也沒有被 refer,所以也回收,最後只留下 closure.age。
: console.log( cat.age(3).age() );
: })();
請問答案是這兩種情況其中之一嗎?@@?
--
Oni devas ami animalojn. Ili estas tiel bongustaj.
One should love animals. They are so tasty.
每個人都應該愛動物,他們是如此美味。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 175.180.52.50
※ 編輯: B9 來自: 175.180.52.50 (06/19 09:52)
推
06/19 09:59, , 1F
06/19 09:59, 1F
→
06/19 10:00, , 2F
06/19 10:00, 2F
→
06/19 10:01, , 3F
06/19 10:01, 3F
→
06/19 10:02, , 4F
06/19 10:02, 4F
→
06/19 11:29, , 5F
06/19 11:29, 5F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
Ajax 近期熱門文章
PTT數位生活區 即時熱門文章