Note: This article is an adaptation (may be a mirror) of the article originally posted at Edujini™ Eduzine™ here.
All the three articles of the series are listed below:
Object Oriented Programming - as defined by Grady Booch - stands on three pillars:
- Declaring variables -
- Basic data types supported -
- All data-types are infinitely flexible
- All objects (references; instances) are infinitely extensible
- Objects are associative arrays
- It's all about functions
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. are another way to implement encapsulation.
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,
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:
function UserProfile(username, password)
this.username = username;
this.password = password;
this.authenticate = function()
if(this.username == 'gvaish' && this.password == 'edujini')
Notice the use of
this keyword. Does it remind you of something? Yes! You got it right...
function is the way to implement the concept of
class, or to speak - encapsulation.
Ok... so, how do we use this new data-type that we just defined? Let's create an 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:
11 function validateUser()
13 var uname = document.getElementById('u').value;
14 var pwd = document.getElementById('p').value;
16 var e = document.getElementById('result');
18 var u = new UserProfile(uname, pwd);
19 var result = u.authenticate();
20 e.innerHTML = 'Result: ' + result;
26 Username: <input type='text' name='u' id='u' />
28 Password: <input type='password' name='p' id='p' />
31 <button onclick='validateUser(); return false;'>Login</button>
33 <div id='result'></div>
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.
validateUser defined at line 11-21 triggers the validation by extracting the values of username and password (lines 13-14).
At line 18,
At line 19, we invoke the method
authenticate that returns a value
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!
- Use of
this keyword within the type definition