Click here to Skip to main content
13,898,650 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


18 bookmarked
Posted 19 Jun 2008
Licenced BSD

Exploring OOPS - JavaScript Style: Part 1 - Encapsulation

, 2 Aug 2008
Rate this:
Please Sign up or sign in to vote.
This article, 1st Part in the series of 3-articles, starts discussion on OOPS implementation in JavaScript. Starting with Encapsulation.


This article, 1st Part in the series of 3-article, starts discussion on OOPS implementation in JavaScript.

Note: This article is an adaption (may be a mirror) of the article originally posted at Edujini™ Eduzine™ here.

All the three articles of the series:

  1. Encapsulation at edujini_005_JavaScript_OO.aspx.
  2. Inheritance at edujini_006_JavaScript_OO.aspx.
  3. Polymorphism at edujini_007_JavaScript_OO.aspx.


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.

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! Look here for all insights about JavaScript functions.

4-Sutras while working with JavaScript

While working with JavaScript, always keep in mind the following, as Gaurav Vaish (yes, that's me) calls them, "4-Sutras":

  1. All data-types are infinitely flexible.
  2. All objects (references; instances) are infinitely extensible.
  3. Objects are associative arrays.
  4. 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", I say.


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:

  1. username: Property to hold the username of the user.
  2. password: Property to hold the password of the user.
  3. 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.

 * (C) 2008, Gaurav Vaish, Edujini Labs Pvt Ltd

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        * (C) 2008, Gaurav Vaish, Edujini Labs Pvt Ltd
 8        *
 9        *
10        */
11       function validateUser()
12       {
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;
21       }
22     </script>
23   </head>
24   <body>
26   Username: <input type='text' name='u' id='u' />
27   <br/>
28   Password: <input type='password' name='p' id='p' />
29   <br/>
31   <button onclick='validateUser(); return false;'>Login</button>
33   <div id='result'></div>
35   </body>
36 </html>


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 11-21 triggers the validation by extracting the values of username and password (lines 13-14).

At line 18, 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 19, 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!


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.

Moving forward...

The next step is look at the next articles on Inheritance and Polymorphism in JavaScript.


This article, along with any associated source code and files, is licensed under The BSD License


About the Author

India India

Gaurav lives in Bangalore, the Silicon Valley of India.

His technical strength lies in having deep understanding of not one or two but bunch of enterprise frameworks.

Lately, he is working on an MVC framework implementation for Android put in open domain at

Today, he is an independent guy:

  • He is a programming language independent guy, well almost. He is proficient in C, C++, Java, C#, VB.Net, C++.Net, JavaScript, PHP, Tcl, Python, Ruby
  • He is an OS independent guy, well almost. Has worked and developed at length on HP-UX, Linux (Redhat / Mandrake), Macintosh (9, 10.x), Windows (NT, 2000, 2003, XP, Vista), Solaris (8, 9, 10); and mobile platforms Android, iPhone, Blackberry
  • He is a target independent guy, well almost. Has worked on thick clients (mainly desktops) as well as thin clients (mainly alternative platforms - Symbian, PalmOS, WinCE, WinXP Embedded, Linux Embedded, Android, iPhone, Blackberry)

Today, his thrust areas are Service Oriented Architecture (implementation expert in Java, .Net and PHP; integration with Mainframe and other legacy environments), Mobile Technologies and RFID.

He holds a Bachelor's Degree (B. Tech.) from IIT Kanpur His major was in EE with specialization in DSP (SSP).

His hobby is listening music, reading books (no, he can't read novels), photography and travelling.

Should you wish to talk to him, you can drop him a mail at gaurav[dot]vaish[at]gmail[dot]com. He generally responds within 24-48 hrs unless there is a compelling reason.

And yeah... here's his personal website:

Smile | :)

You may also be interested in...

Comments and Discussions

GeneralScary Pin
Todd Smith19-Jun-08 7:41
memberTodd Smith19-Jun-08 7:41 
GeneralRe: Scary Pin
mastergaurav19-Jun-08 7:57
membermastergaurav19-Jun-08 7:57 
GeneralIsn't this just a duplicate Pin
Jim Crafton19-Jun-08 6:34
memberJim Crafton19-Jun-08 6:34 
GeneralRe: Isn't this just a duplicate Pin
mastergaurav19-Jun-08 6:36
membermastergaurav19-Jun-08 6:36 
GeneralRe: Isn't this just a duplicate Pin
Jim Crafton19-Jun-08 6:39
memberJim Crafton19-Jun-08 6:39 
QuestionOOPS? Pin
PIEBALDconsult19-Jun-08 6:15
protectorPIEBALDconsult19-Jun-08 6:15 
AnswerRe: OOPS? Pin
mastergaurav19-Jun-08 6:25
membermastergaurav19-Jun-08 6:25 
GeneralRe: OOPS? Pin
uXuf24-Jun-08 17:30
memberuXuf24-Jun-08 17:30 
GeneralRe: OOPS? Pin
mastergaurav24-Jun-08 20:36
membermastergaurav24-Jun-08 20:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190306.1 | Last Updated 2 Aug 2008
Article Copyright 2008 by mastergaurav
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid