Click here to Skip to main content
15,908,264 members
Articles / Programming Languages / Javascript

Programming using objects in JavaScript

Rate me:
Please Sign up or sign in to vote.
2.57/5 (12 votes)
28 May 2007CPOL1 min read 19.7K   12  
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():

HTML
<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:

JavaScript
<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:

JavaScript
<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)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --