Click here to Skip to main content
13,355,335 members (73,555 online)
Click here to Skip to main content
Add your own
alternative version


12 bookmarked
Posted 16 May 2007

Programming using objects in JavaScript

, 28 May 2007
Rate this:
Please Sign up or sign in to vote.
Object oriented programming in JavaScript.


JavaScript supports inheritance. It can support OOP because it supports inheritance through prototyping as well as properties and methods.

Objects work so well because they act just like real life objects - objects have properties and methods. JavaScript gives you the ability to make your own objects for your own applications. With your objects, you can code in events that fire when you want them to, and the code is encapsulated. It can be initialized any amount of times.

Using the code

There are several ways to create objects in JavaScript, and all of them have their place. The simplest way is to use the new operator, specifically, new Object():

<script language="javascript" type="text/javascript">

employee = new Object() = "23975" = "Sachin"

person.details = function() {
    alert("Employee Details: " + + "/" +


The above way does not allow us to reuse the object. We need a way to create an object "type" that can be used multiple times without having to redefine the object every time to meet each particular instance's needs. For this, we create a constructor function:

<script language="javascript" type="text/javascript">

function employee(id,name) { = id; = name;
    this.details = function() {
        alert("Employee Details: " + + "/" + )

employee1 = new employee("23975","Sachin")

employee2 = new employee("23978","Nithin")


Prototype is a type of inheritance in JavaScript. We use it when we would like an object to inherit a method after it has been defined. Think of prototyping mentally as "attaching" a method to an object after it's been defined, in which all object instances then instantly share.

We can extend our original employee() object above with an additional method to change the employee's ID, using prototype:

<script language="javascript" type="text/javascript">
employee.prototype.changeId = function(id) { = id;

newemployee = new employee("23979","Aswin")
newemployee.details() //alerts Employee Details: 23980/Aswin



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
India India
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 29 May 2007
Article Copyright 2007 by SachinKumarK
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid