Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Wednesday, July 24, 2013

JavaScript class and namespace

The following links are the basic link provide the information how to create namspace and class in JavaScript.
The following example is to show how to create basic namespace and class. The namespace is name "NS" then create class in that namespace "Sound". Sound class has instance variable "name". and class variable "Variable". Also has the class method "Method1" and "Method2" which can be used like static method in Java or C#. After that this html page will be processed when document loaded and print out "love story 3".
<!DOCTYPE html>
<html>
 <head>
  <title>Test</title>
  <script type="text/javascript">
  var NS = NS || {};
  
  NS.Sound = function (name) {
   this.name = name;
  }
  
  NS.Sound.Variable = [];
  
  NS.Sound.Method1 = function () {
   NS.Sound.Variable.push(1);
   NS.Sound.Variable.push(2);
   NS.Sound.Variable.push(3);
  }
  
  NS.Sound.Method2 = function () {
   return NS.Sound.Variable.length;
  }
  
  function onLoad() {
   var sound = new NS.Sound("lovestory");
   var div = document.getElementById("content");
   
   NS.Sound.Method1();
   var content = sound.name + " " + NS.Sound.Method2();
   
   div.innerHTML = content;
  }
  
  document.addEventListener("DOMContentLoaded", onLoad, false);
  </script>
 </head>
 <body>
  <div id="content"></div>
 </body>
</html>

No comments:

Post a Comment