Namespaced Javascript-Vorlage

Avatar of Chris Coyier
Chris Coyier am

Selbstausführende anonyme Funktion, die der globalen Variable yournamespacechoice zugewiesen wird. Dies hat den Effekt, alle Funktionen und Variablen privat für diese Funktion zu halten. Um eine Funktion oder Variable offenzulegen, müssen wir sie am Ende der Funktion explizit zurückgeben. Ordnet jQuery als $ neu zu.

var yournamespacechoice = (function ($) {
   var publicfunction;

   function privatefunction() {
       // function only available within parent function
   }

   publicfunction = function publicfunction() {
       // public function available outside of this funtion
   };

   // Expose any functions that we need to access outside of this scope. Use yournamespacechoice.functionName() to call them.
   return {
       publicfunction: publicfunction
   };
}(window.$));