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!

3
  • This is something you really could find out for yourself with a quick visit to Google. Commented Jul 30, 2012 at 13:14
  • I don't think it's possible, the available types are listed in the specification: es5.github.com/#x8. Might depend on your interpretation of "type" though. Commented Jul 30, 2012 at 13:15
  • It all depends on what the word "type" means to you. Commented Jul 30, 2012 at 13:15

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

those are not private properties, but normal variables
wouldn't this.public_method1rather be calles a 'privileged method' and the protoype methods the 'public' ones ?
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)).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.