JavaScript Wo ist der Unterschied?

Hendoul

Commander
Registriert
Apr. 2008
Beiträge
2.162
Hi :)

Eigentlich wollte ich rausfinden, wie man all seine Javascript-Funktionen unter einem gewissen Namen veröffentlicht, so dass man nachher so darauf zugreifen muss -> myLibrary.myFunction()

myLibrary müsste dazu global verfügbar sein? Wie erreiche ich diese Funktionalität?

Gelesen habe ich dann noch folgenden Artikel:
http://www.matthiassommer.it/programming/expose-global-variables-methods-modules-javascript/

Da steht u.a. folgendes:
If you put all your JavaScript methods into one file and import this file in an HTML document via <script type="text/javascript" src="scriptFile.js"></script>, all your methods will reside in the global name space. This will be an important issue later-on.

Und nachdem er aus einem File mehrere gemacht hat:
However, there is still one problem. The functions are not visible in the global namespace. Thereby, we can not access them from outside our application. Just think of a library where you want to expose certain methods which should be visible to the outside world.

Es ändert doch rein gar nichts, nur weil man mehrere Files macht bzgl. dem global Namespace?
Was ändert es denn, wenn ich ein File aufsplitte in mehrere und dann ein paar exports und imports in diesen File brauche?
 
Hallo,

der Unterschied liegt darin, dass er, wie (leider) nur kurz in diesem Satz erwähnt:
That is my motto when I start working on a new project. Therefore, I split this big mess up into a bunch of packages and files which each do one thing, following the Single Responsibility Principle.
die eine große Datei in Module geändert hat.

Module zeichnen sich eben durch ihren eigenen Scope (~Geltungsbereich) aus.

Ein bisschen Überblick könnte das hier bringen: https://www.freecodecamp.org/news/javascript-modules-a-beginner-s-guide-783f7d7a5fcc/

Für dich relevant vor allem "Example 4"

Das ist allerdings ein echtes Umdenken, wenn man bisher einfach alles im globalen Namespace hatte :D
Ich finde den von dir verlinkten Text nicht besonders gut erläutert, Ausgangspunkt ist "a big mess" und Ziel ist eine Webpack-Config mit Modulen + irgendwas mit Eclipse.
Dabei erklärt er die Grundlagen ein bisschen und alles darüber hinaus gar nicht mehr?!

Lg
 
  • Gefällt mir
Reaktionen: Darrel
Zurück
Oben