Javascript Object Oriented Template


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



Copy this code and paste it in your HTML
  1. var MYNAMESPACE = YAHOO.namespace("mynamespace");
  2.  
  3. //CLASS: MYNAMESPACE.MyClass
  4. (function() {
  5. // private
  6. var that = null;
  7. var priv1 = "123";
  8. var priv2 = "ABC";
  9.  
  10. var privMethod = function () {
  11. priv1 += "_priv";
  12. };
  13.  
  14. // constructor
  15. MYNAMESPACE.MyClass = function(par1, par2){
  16. that = this;
  17. priv1 += par1;
  18. priv2 += par2;
  19.  
  20. privMethod();
  21.  
  22. this.prop1 += par1;
  23. };
  24.  
  25. // public
  26. MYNAMESPACE.MyClass.prototype = {
  27. // events
  28. onClassReady : new YAHOO.util.CustomEvent("onClassReady"),
  29. onPubMethod1Loaded : new YAHOO.util.CustomEvent("onPubMethod1Loaded"),
  30.  
  31. // properties
  32. prop1 : "Test1",
  33. prop2 : "999",
  34.  
  35. // methods
  36. pubMethod1: function(p1){
  37. this.onPubMethod1Loaded.fire(this.prop1, this.prop2);
  38.  
  39. return this.prop1 + priv1 + p1;
  40. },
  41.  
  42. pubMethod2: function(p1){
  43.  
  44. }
  45. }
  46.  
  47. // static
  48. MYNAMESPACE.MyClass.statMethod = function () {
  49. YAHOO.log(this);
  50. }
  51. })();
  52.  
  53. MYNAMESPACE.MyClass.statMethod(); // function ()
  54.  
  55. var myObject = new MYNAMESPACE.MyClass("_kkk", "_ppp");
  56.  
  57. myObject.onPubMethod1Loaded.subscribe(function (type, args, me) {
  58. YAHOO.log(this); // window
  59. YAHOO.log(type); // onPubMethod1Loaded
  60. YAHOO.log(args); // ["Test1_kkk", "999"]
  61. YAHOO.log(me); // Object
  62. }, myObject);
  63.  
  64. YAHOO.log(myObject.prop1);
  65. YAHOO.log(myObject.pubMethod1("ioioi"));

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.