Object Constructor Functions
This demonstrates how to create Object instances from functions, and dmonstrates that this can be mixecd with Object Notation.
by Vimla Ramdoo
JavaScript
// Used to creaet an instance called shopper in function notation
var Shopper = function(givenName, familyName, cart) {
this.givenName = givenName;
this.familyName = familyName;
this.cart = cart;
// Method to add an item to the shopping cart
this.addToCart = function(theItem) {this.cart.push(theItem);}
// Method to reset the shopping cart
this.reset = function() {this.cart = [ ];}
// Method to return an invoice as a String
this.invoice = function() {
var str = "Shopper: " + this.familyName + ", " +
this.givenName + "\n\n" ,
sum = 0;
for (var i=0 ; i< this.cart.length; i++) {
str += this.cart[i].description + " $" +
this.cart[i].cost + "\n";
sum += this.cart[i].cost;
}
str += "\ntotal: $" + sum;
return str;
}
}
// Item constructor
var Item = function(description, cost) {
this.description = description;
this.cost = cost;
}
// Create a new instance of a Shopper object
var shopper = new Shopper("Jane", "Doe", new Array());
// Add items to the shopper's cart
shopper.addToCart(new Item ("lamp", 50.00));
shopper.addToCart({description: "chair", cost: 100.00});
shopper.addToCart(new Item ("chair", 100.00));
shopper.addToCart(new Item ("table", 1500.00));
alert (shopper.invoice());
/* Try this:
1. Convert Object notation in line 39 to use constructor function
*/