I write a script to display the message. File notify.js :

 ;(function(){ function Notify(titleText, messageText) { var notify = document.createElement("div"); notify.className = "notify"; var title = document.createElement("div"); title.className = "notify title"; title.innerHTML = titleText; var message = document.createElement("div"); message.className = "notify message"; message.innerHTML = messageText; notify.appendChild(title); notify.appendChild(message); function show(){ document.body.appendChild(notify); } } })(); 

When you connect the script in index.html and when you call Notify("title","message").show() error Notify is not defined and this is understandable, but how to write differently so that there are no conflicts with local scripts? I make a lot of mistakes, tell me which ones? How to organize the code, write the library?

    2 answers 2

    You have locally created the code and ... died, because at the end of the function, its environment is destroyed. The exception is a closure (for example, a link to some data is preserved even after completion of the work).

     // В параметрах передаём модуль и this (глобальный объект, не обязательно window) (function(myModule, global){ // Если есть система зависимостей AMD, добавляем модуль туда if(typeof define === "function" && define.amd) define("logger", [], () => myModule()); // Если же это RequireJS, не будем идти против воли Творца :) else if(typeof module !== 'undefined' && module.exports) module.exports = myModule(); // Если систем сборки нет, значит экспортируем в глобальный объект else global['logger'] = myModule(); }(function(){ let myModule = _ => console.info(`Вывод '${_}' через модуль`); return myModule; }, this)); // Сработает 3-я ветка экспорта logger('Test'); 

    But the standard establishes a more interesting design for the modules, I recommend to get acquainted with it .

      Notify you have defined in the scope of the inside of the cover, it is not visible from the outside. In your case, a pattern module may come up, then an object is returned from the function.

      But in general, ECMAScript now has a standard for modules . This will work if you use something like Babel . You can also use CommonJS require .