Reputation: 4072
Take this code for example:
(function(foo) {
foo.init = function() {};
// other public/private methods here.
return foo;
}(window.FOO = window.FOO || {}));
I call it like so:
FOO.init();
Is it possible to allow the user to define what FOO
is?
In other words, I need to allow multiple instances of window.FOO
; for example, like window.BILLY
and window.BAZ
(or, should it be window.billy.FOO
and window.baz.FOO
?).
In other words, is there an elegant way to (allow the user to) namespace a "namespace" using a variation of the above construct and initialization?
Upvotes: 1
Views: 80
Reputation: 2303
The windows.billy.FOO
and windows.baz.FOO
are preferred.
Have a read through Addy Osmani's Essential JS Namespacing Patterns to get up to speed (most relevant part: Deep object extension).
Cheers!
Upvotes: 2
Reputation: 24576
If I understand you correctly you want to change the above code such that the name of FOO
is dynamic. You can do that, using the [] property accessor:
function initFoo(fooName) {
(function(foo) {
foo.init = function() {};
// other public/private methods here.
return foo;
}(window[fooName] = window[fooName] || {}));
}
initFoo('FOO');
initFoo('BILLY');
But I'm not sure what sense this would make, your example is very abstract.
Upvotes: 2
Reputation: 6613
You may want to look into RequireJS: http://requirejs.org/docs/start.html
It may have the end-user functionality you're looking for.
Upvotes: 1