Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a class in Javascript [closed]

Tags:

javascript

I want to create a class in Javascript. This class should have

  1. private and public variables and functions.
  2. static and dynamic variables and functions.

How this can be done ?

like image 891
Triode Avatar asked Dec 21 '11 16:12

Triode


1 Answers

A good way to create objects that support public and private properties is to use a factory function:

function createObj(){
   var privateVariable = "private";

   var result = {};

   result.publicProp = 12;

   result.publicMethod = function() {
      alert(this.publicProp);
      alert(privateVariable);
   };

   //this will add properties dynamically to the object in question
   result.createProperty = function (name, value) {
       this[name] = value;
   };

   return result;
}

As for static, you can simulate them by putting them on the function itself

createObj.staticProperty1 = "sorta static";

And to see dynamic properties in action:

var obj = createObj();
obj.createProperty("foo", "bar");
alert(obj.foo); //alerts bar
like image 125
Adam Rackis Avatar answered Sep 29 '22 09:09

Adam Rackis