The code of a JavaScript library might get very complex over time. This can be a problem for maintenance and expandability.
When writing a library, you should address two main points:
- Keep the environment clean from global variables and methods to avoid conflicts between different libraries
- Provide public and private methods and variables
The following “template” provides a simple code structure that fulfills those points:
// Unique name of the library.
MyLibrary = function() {
MyLibrary = {};
/*
* Internal variables and methods
*/
var variable = 'value';
function doSomething() {
// do something
}
/*
* Public variables and methods
*/
MyLibrary.myVariable = true;
MyLibrary.myAction = function() {
// do something
}
// Return the library.
return MyLibrary;
}
You can use such a library the following way:
const lib = MyLibrary();
lib.myAction()
if (lib.myVariable) {
alert('really?');
}
Inspiration: https://stackoverflow.com/questions/13606188/writing-a-library-what-structure
Photo by Safar Safarov on Unsplash
Leave a Reply