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
- function Interest(Principal, Rate, Time)
- {
- return (Principal * Rate * Time) / 100;
- }
- console.log("Calculated interest is= " + Interest(5000, 10, 8));
Output 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 - var Interest = function (Principal, Rate, Time)
- {
- return (Principal * Rate * Time) / 100;
- }
- console.log("Calculated interest is= " + Interest(5000, 10, 8));
Output 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
- (function ()
- {
- var x = "Self-Invoking Function";
- })();
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 - jQuery.fn.extend(
- {
- Reverse_String: function ()
- {
- var Text_ = $(this).val();
- var Split_ = Text_.split(" ");
- var Return_ = '';
- for (var count = Split_.length - 1; count >= 0; count--)
- {
- Return_ += Split_[count] + " ";
- }
- returnReturn_;
- }
- })
In the above code we create a function that reverse the string . We will use this function to reverse the value of a textbox.
- $("#btnCreate").click(function ()
- {
- console.log($("#txtName").Reverse_String());
- })
In the above code we called the “
Reverse_String” method on button click event. Let us take a demo.
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 - <divid="div1">
- <spanid="span1">Pankaj Choudhary</span>
- </div>
jQuery Code - <script>
- $(document).ready(function ()
- {
- alert("Count IS:= " + $('#span1').size(function () {}));
- });
- </script>
On button click it finds the count of span element whose id is “
span1”.
Now we extend the “
size” function:
- <script>
- $(document).ready(function ()
- {
- varOld_Obj = $.fn.size;
- $.fn.size = function ()
- {
-
- var Return_ = Old_Obj.apply(this, arguments);
-
- try
- {
-
- $(this).css(
- {
- 'background-color': 'Yellow'
- });
-
- $(this).css(
- {
- 'color': 'Blue'
- });
-
- var Text = 'Property Has changed! ';
- $(this).prepend(Text);
- }
- catch (e)
- {
- console.log(e);
- }
-
- returnReturn_;
- }
- alert("Count IS:= " + $('#span1').size(function () {}));
- });
- </script>
- <style>
After extending the “
size” function, if we call the size function for previous, then we will find the following code.
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 - <script>
- $(document).ready(function ()
- {
- MyFunctions = {
- Sum: function (x, y)
- {
- return x + y;
- },
- Sub: function (x, y)
- {
- return x - y;
- },
- Div: function (x, y)
- {
- return x / y;
- },
- Mul: function (x, y)
- {
- return x * y;
- }
- }
- var a = 20;
- var b = 10;
- 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))
- });
- </script>
Output Thanks for reading the article.