Javascript function namespaces

16/12/2015 03:51

There is good practice to use namespaces in javascripts to prevent calling incorrect function in case of the same function names in various javascript blocks or files. When using namespaces, we call function from that namespace, so we are sure to call the correct one.

We can define functions in variable (Lukas2) or we can use a bit more complicated syntax to prevent functions reloading (Lukas1).

 

<html>
<head>
<script>


(function () {
  if (typeof Lukas1 == "object") {
   return;
  }
  window.Lukas1 = (function () {
   return {
   
    AlertMe: function() {
    alert('Lukas1 namespace');
    },
   
    AddNumbers: function(a, b) {
     alert(a+b);
    }
   }
  })();
 })();

var Lukas2 = {
 AlertMe: function() {
  alert('Lukas2 namespace');
 },
 
 AddNumbers: function() {
  alert('AddNumbers function called');
 }
}


</script>
</head>
<body>
<input type="button" id="btn1" onclick="Lukas1.AlertMe()" value="Lukas1"/>
<input type="button" id="btn2" onclick="Lukas2.AlertMe()" value="Lukas2"/>
</body>