Different Ways To Declare Function In JQuery

In JavaScript / jQuery we can define a function in several ways. We can also create a user defined function just like other jQuery functions for DOM elements. In this article I will explain some methods to declare a function and also explain how to create a user defined function.

Method 1: Basic JavaScript Function

This is a basic way to define a function in JavaScript.

Syntax

functionFunction_Name(Para1,Para2,…..)

Now we create a function that will calculate the interest for given Principal, Rate and Time.

Example

  1. function Interest(Principal, Rate, Time)  
  2. {  
  3.     return (Principal * Rate * Time) / 100;  
  4. }  
  5. console.log("Calculated interest is= " + Interest(5000, 10, 8));  
Output

Basic JavaScript Function

Method 2: Declare Function as Variable Name

A JavaScript function can also be defined using an expression. This function expression can be stored in a variable. After storing the expression in a variable, this variable can be used as a function.

Syntax

Varvariable_name=function(Para1,Para2,….){
   //function expression
}

Now we take previous example and declare function expression in a variable.

Example
  1. var Interest = function (Principal, Rate, Time)  
  2. {  
  3.     return (Principal * Rate * Time) / 100;  
  4. }  
  5. console.log("Calculated interest is= " + Interest(5000, 10, 8));  
Output

Declare Function as Variable Name

Method 3: Self Invoking Function

A self-invoking expression is invoked automatically, without being called. We can’t call a self-invoking function. We have to add parentheses around the function to indicate that it is a function expression. Self-Invoking function do not contain any name.

Example
  1. (function ()  
  2. {  
  3.     var x = "Self-Invoking Function";  
  4. })();  
Method 4: Create own jQuery Function

jQuery provide an excellent way to create a user defined function and use this function just like other jQuery function for DOM elements. The “jQuery.fn.extend” method is used to create user defined function. Here, jQuery.fn is just an alias for jQuery.prototype.

Syntax

uery.fn.extend({
   //function implementation
   return;
})


Example
  1. jQuery.fn.extend(  
  2. {  
  3.     Reverse_String: function ()  
  4.     {  
  5.         var Text_ = $(this).val();  
  6.         var Split_ = Text_.split(" ");  
  7.         var Return_ = '';  
  8.         for (var count = Split_.length - 1; count >= 0; count--)  
  9.         {  
  10.             Return_ += Split_[count] + " ";  
  11.         }  
  12.         returnReturn_;  
  13.     }  
  14. })  
In the above code we create a function that reverse the string . We will use this function to reverse the value of a textbox.
  1. $("#btnCreate").click(function ()  
  2. {  
  3.     console.log($("#txtName").Reverse_String());  
  4. })  
In the above code we called the “Reverse_String” method on button click event. Let us take a demo.

Reverse String
Method 5: Extend Existing jQuery Function

In jQuery, we can extend any existing function by adding some extra functionality. Now we extend the functionality of “jQuery.size()” function. We know that the “size” function return the number of elements in the jQuery object.

Let us take an example.

Html Code
  1. <divid="div1">  
  2.     <spanid="span1">Pankaj Choudhary</span>  
  3. </div>  
jQuery Code
  1. <script>  
  2. $(document).ready(function ()  
  3. {  
  4.     alert("Count IS:= " + $('#span1').size(function () {}));  
  5. });  
  6. </script>  
On button click it finds the count of span element whose id is “span1”.

span1

Now we extend the “size” function:
  1. <script>  
  2. $(document).ready(function ()  
  3. {  
  4.     varOld_Obj = $.fn.size;  
  5.     $.fn.size = function ()  
  6.     {  
  7.         // original behavior   
  8.         var Return_ = Old_Obj.apply(this, arguments);  
  9.         // custom behaviour  
  10.         try  
  11.         {  
  12.             // change background colour  
  13.             $(this).css(  
  14.             {  
  15.                 'background-color''Yellow'  
  16.             });  
  17.             //change text color  
  18.             $(this).css(  
  19.             {  
  20.                 'color''Blue'  
  21.             });  
  22.             // add some text  
  23.             var Text = 'Property Has changed! ';  
  24.             $(this).prepend(Text);  
  25.         }  
  26.         catch (e)  
  27.         {  
  28.             console.log(e);  
  29.         }  
  30.         // return value   
  31.         returnReturn_;  
  32.     }  
  33.     alert("Count IS:= " + $('#span1').size(function () {}));  
  34. });  
  35. </script>  
  36. <style>  
After extending the “size” function, if we call the size function for previous, then we will find the following code.

size

We can see that when we called the size function it returned the count and also changed the “background –color” and “text color” of span element because we extend the functionality of “size” function.

Method 6: Define Function in NameSpace

In jQuery we can assign function in custom namespace. We can add or remove the function from namespace. This mechanism provide the functionality of storing the related function in a namespace.

Example
  1. <script>  
  2. $(document).ready(function ()  
  3. {  
  4.     MyFunctions = {  
  5.         Sum: function (x, y)  
  6.         {  
  7.             return x + y;  
  8.         },  
  9.         Sub: function (x, y)  
  10.         {  
  11.             return x - y;  
  12.         },  
  13.         Div: function (x, y)  
  14.         {  
  15.             return x / y;  
  16.         },  
  17.         Mul: function (x, y)  
  18.         {  
  19.             return x * y;  
  20.         }  
  21.     }  
  22.     var a = 20;  
  23.     var b = 10;  
  24.     alert("Value is 20 and 10 \n" + "Sum of Both value is is= " + MyFunctions.Sum(a, b) + "\n Subtraction of Both value is is= " + MyFunctions.Sub(a, b) + "\n Multiplication of Both value is is= " + MyFunctions.Mul(a, b) + "\n Divison of Both value is is= " + MyFunctions.Div(a, b))  
  25. });  
  26. </script>  
Output

Output

Thanks for reading the article.

 


Similar Articles