How Do JavaScript Closures Work in Magento 2? (Magento Developer Certification)

How Do JavaScript Closures Work in Magento 2? (Magento Developer Certification)

The closure is considered to be the inner function that has access to the variables of the outer function. Every time when executing the outer function, the instance of the inner function containing new references to variables of the outer function is created. Thanks to closure, the inner function remembers all the variables passed to the inner function.

Let’s consider the example of Magento:

Magento 2.1.5 (pub/static/frontend/Magento/luma/en_US/Magento_Catalog/js/compare.js)

Another significant point that should be kept in mind is a leak when dealing with closures. Closure saves a marker on contents enclosed. As a result, closure fixing to DOM element can cause circular dependency and, therefore, memory leak. For example:

The closure contains a marker on the element, a and b, even though closure never uses element. Since element contains marker on closure, it creates a cycle that is never removed by the garbage collector.

 



2 comments

Post a new comment

top
BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *