Beginning Javascript Objects

Read the source and follow along on the displayed page.


Object is a composite data type, like Array. It contains a reference to any object (including those in the DOM).
In addition to the objects from the DOM (window, navigator, browser), there are some commonly used built-in objects:

Here we'll cover creating a custom object. A constructor is a function whose name is the name of the object.

  /*  for executed Javascript code, see source file and look in head */
   
  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
Javascript code follows, see the source file.

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.
  	 /* for actual Javascript code, see source file, look in <body> */
  	
  		text.smhRating = 3;
  		text.picture = new Image();
  		text.picture.src= p1.src;
  		document.write("showing text's picture");
  		document.write("<img src= text.picture.src align='right' id='im1' height=300>");
  		confirm("proceed");
  		
  		document.write("DONE");
  	

current text picture

can't find it

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 />");