I've gotten into the pattern of placing all dependenices that my JavaScript function depends on in the closure of the IIFE.
Pros
-
There's a small performance boost when accessing the variable reference in the closure, rather than climbing up the lexical scope to the root/window object.
-
Another small performance boost if you have namespaced variables that get a little long (i.e. app.calculator.fileExporter), which can be referenced by the variable in the closure (i.e. calcFileExporter). JsPerf Reference
-
A clear, at a glance view at the external classes/functions used.
Cons
-
It can be hard to maintain, and can be hard to be consistent. i.e. Do I really feel like adding another external closure reference, just to use this one call?
-
Larger memory footprint. I'm not sure how large, but there's a larger memory footprint due to this.
My question is:
- Is there concern over a large memory footprint. (i.e. 50+ classes, all having ~3 closure reference variables). These are just insignificant pointers, low in size, right?
- Is this a recommended pattern? I've seen this used for the jQuery/$ , but not often used for other objects.
Example:
app.calc.fileExporter = (function (document, localStorageWrapper, calcFileImporter) {
// Do some stuff!
}(window.document, app.localStorageWrapper, app.calc.fileImporter));
Aucun commentaire:
Enregistrer un commentaire