I am writing a library, and I have all functions being called with “lib.someFunction();” or “lib.someVariable;”. I know I shouldn’t pollute the global namespace, but I want to give users of my library that option. I heard some libraries have an “option” like “installLibrary();” that moves all functions and variables in a class to the global namespace.
This way, only users would prefer so would be able to call “someVariable;” or “someFunction();” directly.
My problem, though, is how to write such a function. Any ideas?
You can do something like the following:
But beware of using anything other than functions here. If you do this and try to adjust parameters on the global/window namespace, they will not get carried back to your library functions and might not get the behavior you want. For example:
An alternative which doesn’t have this restriction would be to apply your library constructor function to the global/window object:
The trouble with that is that you don’t just pollute the global scope with your public API but also with anything that you might have stored in your local closure along the way. That strikes me as way too heavy.
If your library uses something like the revealing module pattern and exposes only functions, then I think the first is pretty straightforward. But as others have said, it may not be wise. At the very most, I would offer this as an option for users but warn against it.