Как создать свою собственную библиотеку JavaScript

Есть много фактов и важных моментов, почему нужно создавать свою собственную библиотеку в javascript:

  • Чувствует себя довольно круто
  • Это хороший способ организовать ваш код
  • Ваш код будет более понятным
  • Поделитесь легко с кем вы хотите
  • Напиши, что тебе всегда нужно один раз

Но всегда, прежде чем писать свой собственный плагин, у вас должно быть четкое представление, почему я хочу написать этот плагин. Рекомендуется, чтобы вы хорошо искали в Google, если уже есть плагин, который делает то, что вы хотите достичь, это будет быстрее, легче чтобы интегрироваться, и это может быть даже лучше, чем то, что вы пытаетесь сделать, помните: мы не хотим воссоздавать колесо, это очень неэффективно, и мы должны избегать его, если нам позволят.

В этом уроке мы собираемся создать простую библиотеку с чистым javascript без прототипирования, вместо этого мы будем использовать нативные объекты.

Если вы хотите узнать, в чем разница между использованием прототипа и управлением объектами вручную, этот пост должен помочь устранить ваши сомнения.

1) Создать базовую структуру

Следующий код создаст глобальную переменную, доступную после выполнения кода, с именем myWindowGlobalLibraryName.

(function(window){
// You can enable the strict mode commenting the following line
// 'use strict';
// This function will contain all our code
function myLibrary(){
var _myLibraryObject = {};
// We will add functions to our library here !
return _myLibraryObject;
}
// We need that our library is globally accesible, then we save in the window
if(typeof(window.myWindowGlobalLibraryName) === 'undefined'){
window.myWindowGlobalLibraryName = myLibrary();
}
})(window); // We send the window variable withing our function
// Then we can call it using
console.log(myWindowGlobalLibraryName);

Так как мы закрываем почти все в анонимных функциях, в случае сбоя нашего кода он не должен повредить весь внешний javascript.

2) Создание пользовательских функций для вашей библиотеки

В этом примере мы создадим пользовательскую функцию журнала, которую мы будем называть myCustomLog.

(function(window){
// You can enable the strict mode commenting the following line
// 'use strict';
// This function will contain all our code
function myLibrary(){
var _myLibraryObject = {};
// Just create a property to our library object.
_myLibraryObject.myCustomLog = function(thingToLog){
console.log("My-Custom-Log > Type of variable : " + typeof(thingToLog));
console.log("My-Custom-Log > Is number : " + !isNaN(thingToLog));
console.log("My-Custom-Log > Length : " + (thingToLog).length);
return console.log(thingToLog);
};
return _myLibraryObject;
}
// We need that our library is globally accesible, then we save in the window
if(typeof(window.myWindowGlobalLibraryName) === 'undefined'){
window.myWindowGlobalLibraryName = myLibrary();
}
})(window); // We send the window variable withing our function
// Then we can call our custom function using
myWindowGlobalLibraryName.myCustomLog(["My library","Rules"]);

3) Если вам нужно, создайте публично недоступные свойства в вашей библиотеке (в области видимости)

Чтобы сохранить настройки или другие виды свойств, не представляющих интереса для пользователя (или просто потому, что мы не хотим, чтобы кто-то их видел), мы можем объявить простую переменную в области действия нашей функции, и она не может быть извлечена за пределами нашей оболочки. ,

(function(window){
// You can enable the strict mode commenting the following line
// 'use strict';
// This function will contain all our code
function myLibrary(){
var _myLibraryObject = {};
// This variable will be inaccessible to the user, only can be visible in the scope of your library.
var settings = {
volume:100,
mute:false
};
// Change a private property
_myLibraryObject.setVolume = function(volume){
settings.volume = volume;
return volume;
};
// Change a private property
_myLibraryObject.setMute = function(muteStatus){
if(typeof(muteStatus) === 'boolean'){
settings.mute = muteStatus;
}else{
console.error("You need to disable or enable the sound !");
}
return settings.mute;
};
// Change a private property
_myLibraryObject.haveSound = function(){
return settings.mute;
};
return _myLibraryObject;
}
// We need that our library is globally accesible, then we save in the window
if(typeof(window.myWindowGlobalLibraryName) === 'undefined'){
window.myWindowGlobalLibraryName = myLibrary();
}
})(window); // We send the window variable withing our function
// Now see the content of your library
console.log(myWindowGlobalLibraryName);
// It should ouput only 3 properties (setMute, setVolume, haveSound)
// And the settings variable can be only be accessed in your library, not outside

Примечание. Несмотря на то, что переменная настроек не может быть извлечена за пределами вашей оболочки, если вы создаете метод, который возвращает переменную, его можно изменить, например, за пределами вашей оболочки.

// Then your variable will be exposed with this method !
_myLibraryObject.getSettings = function(){
return settings;
};
// You can create a get method without expose your variable using something like this
// The object keys will be copied to a new object instead our object.
// Note that you need to achieve this method according to the structure of your variable (or if it's an array)
_myLibraryObject.getSettings = function(){
var mySecurityCopy = {};
for(var i in settings){
if(i)
mySecurityCopy[i] = settings[i];
}
}
return mySecurityCopy;
};

Теперь создайте библиотеку и поделитесь ею с нами!

Ссылка на основную публикацию
Adblock
detector