Creating Objects Using A Constructor Function
for CSCI E3, Harvard University author(s): Larry Bouthillier
by DustyWhite
HTML
<div>
<p>Here we use a constuctor function to create two objects, and use conventional object notation (dot notation and bracket notatation) to access the objects' methods and properties. </p>
<p>Output will appear below:</p>
</div>
<div id="output"></div>
CSS
#output{
width:80%;
border: 1px solid black;
padding: 1em;
}
JavaScript
// create an object type using a constructor function
function AddrBookEntry(f, l, a, e) {
this.fname = f;
this.lname = l;
this.addr = a;
this.email = e;
this.personRole = "student";
this.getFullName = function(){
return this.fname + " " + this.lname;
}
}
// Create two objects using the constructor
var me = AddrBookEntry("Larry","Bouthillier","Massachusetts","[email protected]");
var you = new AddrBookEntry("Any","Student","Cambridge","[email protected]");
// Call on the objects' properties and methods
logMessage(me.fname); // Larry
logMessage(me["fname"]); // Larry
logMessage(me.getFullName()); // Larry Bouthillier
logMessage(you.getFullName()); // Excellent Student
// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id){
if (!id){
id="output";
}
document.getElementById(id).innerHTML += msg + "<br>";
}