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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
define([ "jquery", "jquery/ui", "mage/decorate" ], function($){ "use strict"; $.widget('mage.compareItems', { _create: function() { this.element.decorate('list', true); this._confirm(this.options.removeSelector, this.options.removeConfirmMessage); this._confirm(this.options.clearAllSelector, this.options.clearAllConfirmMessage); }, _confirm: function(selector, message) { $(selector).on('click', function() { return confirm(message);//message variable does not exist in the local scope, that's why the variable is taken from the outer closure (_confitm function) }); } }); return $.mage.compareItems; }); |
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:
1 2 3 |
function foo(element, a, b) { element.onclick = function() { /* use a и b */ }; } |
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.
Magento Custom Development
Take your online store to the next level with BelVG Magento Custom Development
Visit the page
Very informative. Thank you for writing it!
Thanks for sharing!