Beginning Object Orientation (10/24/2011)

Read the source and follow along on the displayed page.

Built-in

Follow this link at w3schools for an overview of built-in Javascript and Browser object.

Custom built

A constructor is a function whose name is the name of the object.

 
  function Book (authorName, title, ISBN, pubDate) {
  	this.author = authorName;
  	this.title = title;
  	this.ISBN = ISBN;
  	this.date = pubDate;
  	}
  
this refers to the current object -- in this case the object that you are declaring:

  var text = new Book ("Heilmnn", "JavaScript with DOM...", "123", new Date("January 1, 2000"));
  

I'm going to create another book, then change the title

Observe how the methods are associated with the custom object

Methods and properties can be added to objects.
To extend a single instance of an object, use the object's name followed by dot followed by new property.

  		text.smhRating = 3;
  		text.picture = new Image();
  		text.picture.src= p2.src;
  		document.write("showing text's picture");
  		document.write("<img src='star.jpg' id='im1' height=30>");
  		confirm("proceed");
  		document.getElementById("im1").src = text.picture.src;
  		document.write("DONE");
  	

To extend already existing custom objects, use the prototype property.

prototype is a built-in property of all objects that specifies the constructor used to make the object. If you modify the prototype of an object, you modify all objects now and future, that have that same prototype.

Add the prototype cost to all books

 
  		Book.prototype.cost = "five dollars"; 	// "" is the default value
  		   		 
  		document.write("text.cost: " + text.cost + "<br />");
  		
  		var text3 = new Book("Dickens", "Christmas Carol", "333", new Date());
  		document.write("text3: " + text3.toString() + " " + text3.cost);
  		
  	

You may only need one object of a particular type -- use new Object() and you don't have to write a constructor.


  		var buddy = new Object();
  		buddy.name = "Koko";
  		buddy.species = "canine";
  		buddy.attitude = "respectful";
  		document.write("<br /&gr;All about buddy: " + 
  			buddy.name + " " + buddy.species + " " + buddy.attitude + "<br />");
  	

Better yet, and very cool, use an object literal (as we can use for associative array):

  		var rascal = {name:"Sevig", species:"dog", attitude:"hoping to replace me"};
  		document.write("<br />all about that rascal: " + rascal.name + " " + rascal.species + " " + rascal.attitude
  			+ "<br />");
  	

Group exercise IF TIME PERMITS!

  1. Define an object for a 2X2 array of states (0 - 2).
  2. Given the following state transition table, add a method that will change state of each cell.
    Old "a" "b"
    0 0 1
    1 1 2
    2 2 0
  3. Add a method to output the grid using innerHTML.