Object Notation example

This is a demonstration of Object Notation, in which comma separated name:value pairs are encolsed in curly braces, to define both object properties and methods.

JavaScript

// Create an object instance called shopper in Object Notatoin
var shopper = {
    givenName: "Jane",      // Given name of shopper
    familyName: "Doe",      // Family name of shopper
    cart: [ ],              // Cart initially empty
    
    // Method to add an item to the shopping cart
    addToCart: function(theItem) {this.cart.push(theItem);},
    
    // Method to reset the shopping cart
    reset: function() {this.cart = [ ];},
    
    // Method to return an invoice as a String
    invoice: function() {
          var str = "",
              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;
          }
};


shopper.addToCart({description: "lamp",  cost:   150.00});
shopper.addToCart({description: "chair", cost:  100.00});
shopper.addToCart({description: "chair", cost:  100.00});
shopper.addToCart({description: "table", cost: 1500.00});

alert (shopper.invoice());