Friday, July 16, 2010

Object oriented Javascript

In this blog, I will try to explore how to perform basic object oriented development using Javascript.

Lets explore by a sample shopping cart application. In this we will have

  1. Items which represent shopping items which will have attributes like item name, Price per Unit, Quantity, and method Total Price which will return Total sub price of particular Items.
  2. Customers can Add Multiple Items to Shopping Cart. This will support two behaviors, adding items to cart, TotalPrice which will return total price of items selected into cart.

<script language=javascript>
//Class representing Item.
function Item(productName,pricePerUnit,numberOfUnits) {
this.ProductName = productName;
this.PricePerUnit = pricePerUnit;
this.NumberOfItems = numberOfUnits;
//Total Price Method will return computed total price of this item
this.TotalPrice = function () {
return this.PricePerUnit * this.NumberOfItems;
//Class representing Shopping Cart which will hold all items
function ShoppingCart() {
//internal variable holding all items
var Items = new Array();
//Method which will add item to shopping cart.
this.AddItem = function (ShoppingItem) {
Items[Items.length++] = ShoppingItem;
//Method which will return computed Total price of all items in cart.
this.TotalPrice = function () {
var totalPrice = 0;
for (var i = 0; i <>
totalPrice += Items[i].TotalPrice();
return totalPrice;

var soapItems = new Item("Pears",10,10);
var foodItems = new Item("Lays", 20, 10);
var cart = new ShoppingCart();
alert("Total Price :" +cart.TotalPrice());

In JavaScript classes can be defined using functions. You can alter this definition by accessing function prototype later at any point of time. We will see more in future posts.

No comments: