Weak Methods September 29, 2006
Many times you would pass bound methods to other functions, as callbacks (i.e., to simulate events,
etc.). However, bound methods (the instancemethod
type) hold a strong reference to their owning
instance (im_self
), which means the existence of a bound method is enough to hold the instance
“alive”, even though your code has lost all references to it.
Sometimes it’s the desired behavior – but not always. This nifty decorator will solve the problem
by returning a “weakly-bound” method, which means the method will not hold the instance alive.
You’ll get ReferenceError
if you try to invoke the method, after the instance has died.
Code
Example
And when we delete the instance f
: