Introduction
As promised in one of the earlier articles, we discuss about how the various pillars of OOPS are implemented in JavaScript.
Obect Oriented Programming - as defined by Grady Booch - stands on three pillars:
- Encapsulation
- Inheritance
- Polymorphism
Here, we explore how all three - Yes! All Three Pillars of OOPS - are implemented in JavaScript.
Downloads
The downloads are available in the Downloads area.
Getting Started
To get started, it is assumed that you are already familiar with basic JavaScript. If not you can look on the web for some tutorials on JavaScript 101 tutorials or the like. To be specific, the following fundamentals are assume:
- Declaring variables -
var keyword.
- Basic data types supported -
Object, Array, Boolean, Number, String and Function.
- Writing functions - well, you got to be really very strong in functions!
4-Sutras while working with JavaScript
While working with JavaScript, always keep in mind the following, as Gaurav Vaish calls them, "4-Sutras":
- All data-types are infinitely flexible.
- All objects (references; instances) are infinitely extensible.
- Objects are associative arrays.
- It's all about functions.
"In JavaScript, whenever you run into any problem related to implementation or structuring of the code, these four sutras will help you out", says Gaurav.
Encapsulation
Encapsulation - in simplest terms - can be defined as putting the related items together. Structures in C is a way to implement encapsulation. Classes in C++, Java, C# etc is another way to implement encapsulation.
Let us see how encapsulation is implemented in JavaScript.
Welcome, Functions!
Gaurav's 4th Sutra comes into action here - "It's all about functions".
Let us define a data-type UserProfile that encapsulates the following three items:
username: Property to hold the username of the user.
password: Property to hold the password of the user.
authenticate: Method to authenticate the user. Returns true if successful, false otherwise.
Let us implement the UserProfile with a constructor that takes the two properties as parameters and initializes itself. Create a file UserProfile.js (strictly speaking, the filename doesn't really matter) with the following code.
/**
* Part of the Eduzine (http://eduzine.edujini-labs.com) Articles.
*
* Downloads available at http://downloads.edujini-labs.com
*
* (C) 2008, Edujini Labs Pvt Ltd
* http://www.edujini-labs.com
*/
function UserProfile(username, password)
{
this.username = username;
this.password = password;
this.authenticate = function()
{
if(this.username == 'gvaish' && this.password == 'edujini')
{
return true;
}
return false;
}
}
Notice the use of this keyword. Does it remind you of someting? Yes! You got it right... function is the way to implement the concept of class, or to speak - encapsulation.
Test Case
Ok... so, how do we use this new data-type that we just defined? Let's create a HTML file that will serve as the playground for our case-studies around the UserProfile. Create a file UserProfile.html (again, filename is not important at all) with the following content:
1 <html>
2 <head>
3 <title>OOPS in JavaScript- Encapsulation</code>
4 <script language='javascript' type='text/javascript' src='UserProfile.js'></script>
5 <script language='javascript' type='text/javascript'>
6 /**
7 * Part of the Eduzine (http://eduzine.edujini-labs.com) Articles.
8 *
9 * Downloads available at http://downloads.edujini-labs.com
10 *
11 * (C) 2008, Edujini Labs Pvt Ltd
12 * http://www.edujini-labs.com
13 */
14 function validateUser()
15 {
16 var uname = document.getElementById('u').value;
17 var pwd = document.getElementById('p').value;
18
19 var e = document.getElementById('result');
20
21 var u = new UserProfile(uname, pwd);
22 var result = u.authenticate();
23 e.innerHTML = 'Result: ' + result;
24 }
25 </script>
26 </head>
27 <body>
28
29 Username: <input type='text' name='u' id='u' />
30 <br/>
31 Password: <input type='password' name='p' id='p' />
32 <br/>
33
34 <button onclick='validateUser(); return false;'>Login</button>
35
36 <div id='result'></div>
37
38 </body>
30 </html>
Analysis
Let's just analyze the code that we just wrote.
We have designed a simple form comprising of inputs for username and password, and a button to trigger validation.
The function validateUser defined at line 14-24 triggers the validation by extracting the values of username and password (lines 16-17).
At line 21, UserProfile is instantiated. Notice a very important thing - the function definition has been used as the constructor. Yes! That's where functions are so important in JavaScript. The functions in JavaScript are higher order functions (similar to that in Smalltalk), that can be used to retain the state.
At line 22, we invoke the method authenticate that returns a value true or false depending upon what we enter in the form.
So, go ahead and try out with different combinations of username and password, and checkout the results!
Summary
In this article we learnt how encapsulation is implemented in JavaScript. To summarize, we explored the following:
- Encapsulation in JavaScript.
- Use of
this keyword within the type definition.
- Defining properties and methods in JavaScript.