Update: I've wikified this so it can become a more useful resource.
What is the best way to emulate classes (and namespaces) in Javascript?
I need to create a Javascript library and have limited experience with the language. I always thought that it had native support for classes, but it is less related to Java than I had assumed. It seems that everything in javascript is actually a function.
What I have found out so far makes a lot of sense with it being a dynamic weakly typed language, but this makes it a bit of a departure for people who are used to having a strongly typed language and using a compiler to spot our errors :)
I mainly work in C# and Java, and was hoping for something syntacticaly similar so the library would look familiar for our other C# developers that will have to maintain it.
I have the following sort of code which works, but was wondering what other developer's takes would be on this. What are the alternatives? Is there a way that is better? Is there a way that is more readable?
I understand that what I want is something similar to C# or Java when I should just accept the fact that this is Javascript, but my aim is to try to ease the learning curve for other developers by making it more familiar and intuitive for them.
//perform the namespace setup (this will actually be done with checking
//in real life so we don't overwrite definitions, but this is kept short
//for the code sample)
var DoctaJonez = new function();
DoctaJonez.Namespace1 = new function();
/**
* Class description.
*/
DoctaJonez.Namespace1.SomeClass = function()
{
/**
* Public functions listed at the top to act like a "header".
*/
this.publicFunction = privateFunction;
/**
* Private variables next.
*/
var privateVariable;
/**
* Finally private functions.
*/
function privateFunction()
{
}
}
//create an instance of the class
var myClass = new DoctaJonez.SomeClass();
//do some stuff with the instance
myClass.publicFunction();