Wednesday, September 4, 2013

OOP with JavaScript

Object Oriented Programming, short called OOP, can be done on different levels. JavaScript can be made OOP too. Normally you write based on the function what you need. For example:

$(".btn").click(function(){
    alert("Button is clicked");
});

For creating a new class with JavaScript you need to start with this:

var MessageBox = function() {
   //Methods and stuff
};

Now we have created a new class. The name of the class is MessageBox. Now we want to add a public method to the class. Lets call the method AlertDefault. The AlertDefault method will call the alert with a static text: "I am a default message"
For defining a public method you need to add this to the method name. So this will be:

this.AlertDefault = function() {
   alert("I am a default message");
};

But maybe we want to have our custom message to give to the alert. So we want to add an argument to our second method. Lets call this method AlertMessage. The implementation will be almost the same, however the argument is put in the alert.

this.AlertMessage = function(message) {
   alert(message);
};

The complete code will be:

var MessageBox = function() {
   this.AlertDefault = function() {
       alert("I am a default message");
   };
 
   this.AlertMessage = function(message) {
       alert(message);
   };
};

Now we have created our class we want to check if everything is working fine.

First we need to create a instance of the MessageBox. Then we can call the AlertDefault and the AlertMessage.

var messageBox = new MessageBox();
messageBox.AlertDefault();
messageBox.AlertMessage("I am a custom message");

No comments:

Post a Comment