Click here to Skip to main content
Click here to Skip to main content

Programming using objects in JavaScript

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

Introduction

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()
employee.id = "23975"
employee.name = "Sachin"

person.details = function() {
    alert("Employee Details: " + employee.id + "/" + employee.name)
}

//-->
</script>

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) {
    this.id = id;
    this.name = name;
    this.details = function() {
        alert("Employee Details: " + this.id + "/" + this.name )
    }
} 

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

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

//-->
</script>

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) {
    this.id = id;
}

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

//-->
</script> 

License

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

Share

About the Author

SachinKumarK
Web Developer
India India
No Biography provided

Comments and Discussions

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