Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Myfunc=_emptyFunc vs Myfunc=null

If I want to release a function called Myfunc
What is best way to achieve such task?
_emptyFunc=function(){}

like image 536
Lanston Avatar asked Dec 28 '25 20:12

Lanston


2 Answers

_emptyFunc is callable while calling null throws a TypeError:

js> _emptyFunc=function(){}
(function () {})
js> _nullFunc=null;
null
js> _emptyFunc()
js> _nullFunc()
typein:5: TypeError: _nullFunc is not a function

So using a no-op function has the advantage that you can simply call it unconditionally instead of having to check if it's not null/undefined and possibly even test if it's something callable.

Using null or undefined has the advantage that your code can avoid doing stuff only necessary when a callback is passed.

If you actually plan to allow the JS engine to release the memory used by whatever function was stored in the variable before, set it to null. Assigning a different function will also remove the (possibly) last reference to the function and thus allow the GC to collect it but you'll have a new function that obviously uses some memory, too.

like image 160
ThiefMaster Avatar answered Dec 31 '25 08:12

ThiefMaster


Set MyFunc to null, that will cause the GC to collect the Function object if there are no more accessible references to it. Generally you don't need to do such thing.

like image 35
Ankur Avatar answered Dec 31 '25 09:12

Ankur