Home
Blog
Contact
Mailing List
Software
Blog
Twitter
|
<< 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) {
this.name = name;
this.age = age;
this.weight = weight;
}
// This is the same as a property in a language such as Java
Dog.prototype.getWeight = function() {
return(this.weight)
}
// An example of a "true" method
Dog.prototype.call = function() {
return("Come here " + this.name);
}
// This is an example of a class method that takes 2 parameters
Dog.prototype.pet = function(times, myname) {
alert(myname + " just pet " + this.name + " " + 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
alert(myDog.getWeight());
// Get weight as a field
alert(myDog.weight);
// Call the dog
myDog.call();
// Tom pets the dog 5 times
myDog.pet(5, "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.
Tom.
Tags
JavaScript
Related Blogs
Using JavaScript intellisense in Visual Studio 2008
Disabling (and setting) the tab stop of a browser in Firefox and MSIE
Differences including javascript file in MSIE and Firefox
Comments
Currently no comments.
Add A Comment
Name:
URL:
Email Address: (not public, used to send notifications on further comments)
Comments:

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