Read the source and follow along on the displayed page.
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 />");
Old | "a" | "b" |
0 | 0 | 1 |
1 | 1 | 2 |
2 | 2 | 0 |
innerHTML
.