Currently, I am developing a JavaScript library where it is crucial to avoid polluting the global namespace by containing all variables within one or two global variables. However, I have encountered a unique situation that requires the use of closures, but my usual approach has not been effective. Despite searching extensively, I have only found the traditional closure method which I typically rely on.
[...]
addFilters: function(filters) {
for(filter in filters) {
this.filters[filter] = filters[filter];
this.Image.prototype[filter] = function() { //closures, how do they work?
return (function(image, filter, arguments) {
image.addQueue(filter, arguments);
})(this, filter, arguments);
};
}
},
[...]
In the given code snippet, the Image.prototype functions and image.addQueue are failing to properly capture the value of 'filter', resulting in it being set to the last filter in the iteration each time.
To view the complete code with relevant sections highlighted, visit: http://pastebin.com/UVFTVPkh
For a live demonstration, you can access it here: