Static and Instantiable Classes in JavaScript


/ Published in: JavaScript
Save to your folder(s)

Simple template for setting up classes in JS


Copy this code and paste it in your HTML
  1. /** InstantiableClass */
  2. var InstantiableClass = function(arg1, arg2) {
  3.  
  4. this.aProperty = "value";
  5. this.anotherProperty = "another value";
  6.  
  7. this.init = function(someArg, isAnotherArg) {
  8. //do some initializiation.
  9. if (isAnotherArg) {
  10. this.anotherProperty = someArg;
  11. }
  12. };
  13.  
  14. this.someMethod = function() {
  15. //do something
  16. var localVar = this.aProperty + " " + this.anotherProperty;
  17.  
  18. return localVar;
  19. };
  20.  
  21. this.init(arg1, arg2);
  22. }
  23.  
  24. var myObj = new InstantiableClass("Jumped over the lazy dog", true);
  25. myObj.aProperty = "The quick brown fox";
  26. myObj.someMethod(); //will return "The quick brown fox Jumped over the lazy dog"
  27.  
  28. var myNextObj = new InstantiableClass(null, false);
  29. myNextObj.aProperty = "Hello";
  30. myNextObj.someMethod(); //will return "Hello another value"
  31.  
  32.  
  33.  
  34. /** StaticClass */
  35. var StaticClass = {
  36.  
  37. aProperty: "value",
  38. anotherProperty: "another value",
  39.  
  40. someMethod: function() {
  41. //do something
  42. var localVar = StaticClass.aProperty + " " + StaticClass.anotherProperty;
  43. return localVar;
  44. }
  45.  
  46.  
  47. };
  48.  
  49. StaticClass.aProperty = "Lazy dogs";
  50. StaticClass.anotherProperty = "let foxes jump over them";
  51. StaticClass.someMethod(); // will return "Lazy dogs let foxes jump over them"

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.