JavaScript Classes [index]
We'll start off by revisiting some basics of JavaScript classes.
As a simple use-case, let's imagine we want to create a class that allows us to define a circle, and calculate its circumference.
To define a JavaScript class, just create a function (which is the constructor), pass it a parameter, and store this value:
function Circle(radius) {
this.radius = radius;
}
Note the following:
- the class name,
Circle
, has an upper-case first letter – this is the convention used for defining a class - the parameter
radius
and the instance variableradius
both have a lower-case first letter - and will be stored on the instance of the class by adding it to the
this
object - these naming conventions (and others on this page) are used not just in JavaScript, but in most other object-oriented languages
Thinking ahead, we know that in order to calculate the circumference of the circle (and possibly later add a method to calculate the area), we will need the value of π. This does not need to be added to every instantiation of the Circle
class, so we can make it a static property:
Circle.PI = 3.14;
Note the convention of using all upper-case letters for a property that will be used as a constant.
In the real world, we would use
Math.PI
, but here we are adding our own value for π to demonstrate the use of static properties on a class.
We can now add an instance method to calculate the circumference:
Circle.prototype.circumference = function () {
return 2 * Circle.PI * this.radius;
}
Note the following:
- the convention of naming a class method with a lower case first letter
- we want to have a distinct
circumference()
method for each instance of this class, so we add the function to theprototype
object of the class – compare this with the way we added the static propertyPI
, above - we reference the static property
PI
by referring toCircle
- and the instance variable
radius
via thethis
object
Now we are ready to use the class we have defined, so firstly we create an instance of it:
var disc = new Circle(3);
Note the following:
- the convention of naming an instance of a class with a lower-case first letter
- we pass the value
3
as the parameter to the constructor, which will be used as the value for the radius of this instance ofCircle
Now that we have an instance of the Circle
class, we can calculate the circumference of it:
disc.circumference();
And that's it!
So to recap, the final definition of Circle
class will look like this:
function Circle(radius) {
this.radius = radius;
}
Circle.PI = 3.14;
Circle.prototype.circumference = function () {
return 2 * Circle.PI * this.radius;
};
It would be useful to have a method to calculate the area of the circle too.
Add an instance method to the Circle
object called area()
to accomplish this.
You already have the disc
instance of Circle
… do you need to create a new instance of the class in order to see the area()
method working?