Advanced Classes and OOP Objects

There are times when functions just aren't enough and we need a nice OOP (object oriented programming) script that is organized using classes and objects, and will help us debug a lot of problems. In this JavaScript Class tutorial, we will show you a simple example of how we can use classes to calculate the circumference and area of a circle.

The concept of OO (Object Orientation) is very simple; the idea is that you review your code and look for anything repetitive and anything that may have a simpler way of being coded. For example, if you create five images dynamically using javascript, and they all have a number indicating which number image it is, then you might as well just put it in a loop. Another example, would be if you had a bunch of functions that all parsed a few variables, just make another function that parses the variables and use that function in each of your functions. The object is to condense your coding, simplifying, and making sure you make reusable code.

We will use the property called "prototype" to make sure our properties are never deleted, and can always be accessed.

function createCircle(radius){
 this.radius = radius;
 this.pi = 3.14;
}
createCircle.prototype.circ = function(){
 return ((2*this.radius)*this.pi);
}
createCircle.prototype.area = function(){
return ((this.radius*this.pi)*(this.radius*this.pi));
}

This is our class, we first have the radius which we define when we
call createCircle(). We define it as this.radius, and this.pi is 3.14,
which is the value of pi. We create another function, by setting the
property named "circ" using prototype to make sure it doesn't get
deleted later. Thus, when circ is accessed, like this: circ(), it will
return the 2pi r, which is the formula for the circumference.

Same concept for area except that it is the area formula.

Now to access these we use these commands. In a function first define the class:

var circle = new createCircle(5);

Then define which function to use in this direction:

var circleCircumference = circle.circ();
var circleArea = circle.area();

Now those two variables contain the answers to the formula. All you
have to do is make a function to define the class and then get the
answers then write it somewhere. Perhaps make a button with some
onclick commands.

Classes are very simple in JavaScript and essential to program with OOP. Always use it for efficiency, speed, and organization. In addition, debugging will be much easier.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.