1

Possible Duplicate:
How to “properly” create a custom object in JavaScript?

Is it possible to construct new types in Javascript? If "everything is an object", then are object constructors what you use for constructing new types? If so, this makes object constructors also type constructors, right? The help is very much appreciated, and good morning Stack Overflow!

Community
  • 1
  • 1
Leila Hamon
  • 2,505
  • 7
  • 24
  • 32

1 Answers1

4

You can use following code to create new Class and add methods and properties to that.

function ClassName() {

   //Private Properties
   var var1, var2;

   //Public Properties
   this.public_property = "Var1";

   //Private Method
   var method1 = function() {
      //Code
   };

   //Privileged Method. This can access var1, var2 and also public_property.
   this.public_method1 = function() {
      //Code
   };
}

//Public Property using "prototype"
ClassName.prototype.public_property2 = "Value 2";

//Public Method using "prototype"
//This can access this.public_property and public_property2. 
//But not var1 and var2.
ClassName.prototype.public_method2 = function() {
   //code here
}

//Create new Objects
var obj1 = new ClassName();
//Access properties
obj1.public_property1 = "Value1";

You can also extend exiting Classes.

Check on Crockford's website

Thanks to Glutamat and Felix Kling

Community
  • 1
  • 1
Sasidhar Vanga
  • 3,384
  • 2
  • 26
  • 47
  • those are not private properties, but normal variables – Esailija Jul 30 '12 at 13:21
  • wouldn't `this.public_method1`rather be calles a 'privileged method' and the protoype methods the 'public' ones ? – Moritz Roessler Jul 30 '12 at 13:22
  • 4
    I would refrain to talk about "private" and "public" since JavaScript does not support visibility of properties. Local variables can be used to simulate private properties to *some* degree, but it's far away from what other languages provide (since it's just a hack, and I don't understand why people are trying to force something into the language which it was not made for (but that's my personal opinion)). – Felix Kling Jul 30 '12 at 13:22