How Do I Namespace Javascript Code With Or Without Iifes?
I have been reading up on namespacing, Object literals, IIFEs, etc. and I'm trying to understand which of the following is the right way to namespace JavaScript code? Namespace wit
Solution 1:
IMHO the best way is to use CommonJS standard, from your code I can see that you are already using EcmaScript6, so the best way will be to use ES6 modules.
In my own projects I use browserify - it allows me to use nodejs/CommonJS modules:
// module1.jsexports.foo = function(value) {
return value + x;
};
exports.CONST = 1;
// module2.jsvar m1 = require('module1');
m1.foo();
All approaches presented by you, are roughly equivalent, personally I like revealing-module-pattern, and try to use it whenever I cannot use CommonJS. I also like to move return statement at the beginning of the module, it help readability:
varMyModule = (function() {
'use strict';
return {
foo: foo
};
functionfoo() {
return1;
}
}());
Another important issue is to have entire module code enclosed in IFFE, especially when you use strict mode
and you concatenate js files.
OK this may not be the answer for your question, but maybe it help you to see the bigger picture...
Post a Comment for "How Do I Namespace Javascript Code With Or Without Iifes?"