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

Jun 7, 2017119Yan Strunevskiy
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)

Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Igor

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.

 


Partner With Us Looking for a partner that will help you to grow your business? We are the right company to develop your webstore. Feel free to get in touch with us. We will be happy to discuss your business opportunities and provide you with a Free Quote. Talk to Igor

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 *