Node.js - why anonymous callbacks

I am studying node.js and noticed that almost all callbacks are embedded as anonymous callbacks in the function. Is there any specific reason for this?

I think that using the named callback and defining it as a local function has 2 advantages: 1. it is cleaner and does not turn the function into one giant block of code 2. given the corresponding name, it acts as documentation - a description of what the callback should do

+7
source share
1 answer

When using named functions in the global scope as callbacks, the area in which the function is named can lead to the function being stored in memory and preventing its garbage collection. This is one of many ways to cause a memory leak in your application. Anonymous functions, on the other hand, are flagged for the GC immediately after they are completed, and anything that has not been returned (there may also be a closure) will be automatically flagged for garbage collection.

Consider a rather complicated jQuery plugin. Before generating and returning the actual object that is the subject of the plugin, you may need to create dozens of variables that contain temporary state data. If this was not done in IIFE (immediately called a functional expression: an anonymous function that immediately executes), this variable "seeps" into the global scope. JavaScript data remains in memory if there is any one variable or closure that still references it. Since these variables β€œleaked” to the global scope, they will remain in memory until this tab / window is closed. When defined inside IIFE, certain variables get stuck in the area of ​​a local anonymous function. Thus, when the function completed execution, the variables are "gone" and their data no longer has references. The JS Engine garbage collector notices that this specific data in memory is no longer mentioned, and marks it for deletion, freeing up occupied memory for other data.

So, if you named your functions and you call them only once, perhaps they uselessly take up memory. If they are anonymous, they will return the memory after execution, reducing the application overhead.

This is essentially a description of how most dynamic languages ​​work, and why they are more popular than static languages ​​such as C, where you need to track every memory allocation you select and delete them when you no longer need them (exercise itself by itself, deciding how long you need data is not always trivial).

+6
source

All Articles