Wednesday, December 05, 2012

Functions vs. Methods in JavaScript with Encapsulation!

Hi Folks,

I found something interesting to share with all of you in Javascript. Functions in javascript as we all know is defined with function keyword while Method in Javascript is a function but can have a scope and you can hide it as we do in object oriented programming. I will be showing 2 examples that implement function versus method in your web page to add 2 numbers.

1) Function to add 2 numbers in Javascript:

In your script tag, this is the declaration of the function:

<script language=javascript >
function myfunction() {
document.getElementById('txtResult').value = parseInt(document.getElementById('Text1').value) +                                             parseInt(document.getElementById('Text2').value);
</script>

My page, see the result after you change the second text box:

<p>Using Functions</p><input type="text" id="Text1" /><br /><input type="text" id="Text2" onchange="myfunction();" /><br /><input type="text" id="txtResult" /><p>

2) Method to add 2 numbers using Methods:

<script language=javascript >
// Methods
var ops = {

add: function AddTwoNumbers() {
                              document.getElementById('txtResult2').value =
                              parseInt(document.getElementById('Text3').value) +
                                 parseInt(document.getElementById('Text4').value);               
                                               }
         };</script>

My page:

<p>Using Methods</p><input type="text" id="Text3" /><br /><input type="text" id="Text4" onchange="ops.add();" /><br /><input type="text" id="txtResult2" />

You will see that we implemented the add function that has the scope within ops object, and in this way you can design and organize your functions within different scopes and with that being said you implement encapsulation for your methods!.

Anoter note, you gave an alias to your function with "add" alias name and this is not the actual name of the method since if you try to call the method as AddTwoNumbers you won't be able to do that.

The running application:



Hope this helps!

No comments: