How to create class and methods using javascript?

Generally we have used classes and methods in programming languages only.

But we can also use “oops concept”  in scripting language also. So now in your mind question will arise that how to use these things in javascript.

This is also very simple to create classes and methods in javascript.

Below is a simple example:

var CommonClass = function(){

}

jQuery.extend(CommonClass.prototype, {

firstMethod: function(){

// Your logic will be here in this method.

},

secondMethod: function(){

// Your logic will be here in this method.

},

});

Above is the simple code snippet for creating classes and methods using javascript. In above code commnClass is the name of class.

 

In this class there are two methods.

 

Now the question is how to call these methods.

 

Below is the code snippet to use the methods.

Just create the object of class like as other programming languages. And then call the method.

 

 

 

jQuery(document).ready(function(){

var common =  new CommonClass();

common.firseMethod();

});

 

 

How to use try and catch in javascript

 

In above code we can also use try and catch and can show the error messages in console or using alerts.

 

 

jQuery.extend(CommonClass.prototype, {

firstMethod: function(){

try{

// Your logic will be here in this method.

}catch(err){

Alert(err.message);

}

},

secondMethod: function(){

try{

// Your logic will be here in this method.

}catch(err){

Alert(err.message);

}                                                                                              },

});

 

So try and catch will be helpful to show error messages on run time using this we can easily detect the errors in our file.