开发者

Assign to a variable inside a closure a reference to the closure - does it leak?

I am looking at some JS ViewModel code that uses this pattern to be able to reference the outer closure in case whatever library changes the "this" pointer when invoking a function as a callback (gotta love JavaScript):

开发者_Python百科function FruitViewModel {
   var that = this; // <-- HERE

   this.someCallBack = function () {
      that.utilityFunction();
   };

   this.utilityFunction = function () { }
}

My question is: Will this cause a memory leak or will it be implementation specific? (e.g. if garbage is collected inside out versus outside in)

Edit: Please assume that at the point when the GC considers this object for collection nothing holds a reference to someCallBack.


The garbage collector is clever enough to detect such cycle references. So it won't leak.


In all JS engines, the object will not be collected until all functions declared in the parent function are no longer referenced.

I am not aware of any GC bugs relevant here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜