Mailing List



NerdyHearn - Blog

<< Back To All Blogs

JavaScript Classes: A quick rundown

Wednesday, January 9th, 2008

I have recently been doing a lot of work with classes in Javascript so I figured I would give a quick rundown.

Javascript classes do not work the same as traditional OOP classes such as PHP, C#, Java, and the whole bunch of them. Javascript does not have the concept of static methods and properties, per se, as most OOP programming languages do. Javascript does however support polymorphism, properties, and member methods, as well as constructors.

Javascript classes are built on the basis of prototypes. A class is declared just like a function would be declared in normal javascript situations. Properties are declared in the constructor of the class. Methods are declared using the prototype syntax. Let's look at a quick example of a class dog, that will have a few properties, and a few methods, as well as a constructor.

// This is the constructor, and the member variable declarations, wrapped up together
function Dog(name, age, weight) { = name;
this.age = age;
this.weight = weight;

// This is the same as a property in a language such as Java
Dog.prototype.getWeight = function() {

// An example of a "true" method = function() {
return("Come here " +;

// This is an example of a class method that takes 2 parameters = function(times, myname) {
alert(myname + " just pet " + + " " + times + " times!");

Using the above example would be done as follows:

// Instantiate the class
var myDog = new Dog("Scooter", 3, 10);

// Get weight as a property

// Get weight as a field

// Call the dog;

// Tom pets the dog 5 times, "Tom");

This is a rundown of the very basic functionality of classes, and there are many more in-depth topics relating to classes in javascript.

There are also a number of different ways to actually declare and use classes, such as creating a new function (which would be the class) and declaring other functions within that function (which would be the methods, properties, etc).

That's all for now folks.




Related Blogs

Disabling (and setting) the tab stop of a browser in Firefox and MSIE
Differences including javascript file in MSIE and Firefox
Javascript XMLHttp requests: Fixing the data necessary to complete this operation...
Using Ext JS in SharePoint... a tip


Currently no comments.

Add A Comment



Email Address: (not public, used to send notifications on further comments)


Enter the text above, except for the 1st and last character:

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers