Video6.5 - Basic Objects and Methods Example
for CSCI E3, Harvard University author(s): Larry Bouthillier
by DustyWhite
HTML
<h3>Video6.5 - Basic Objects and Methods Example</h3>
<p>Here we create two objects using object literals. Each one has a printMe() method, which outputs a summary of the object as a string.</p>
<p>On line 42, we have a printObject() function, which accepts an object as a parameter, and if it has a printMe() method, calls it and writes the resulting string to the page.</p>
<p>On lines 52-53 we call printObject() on each of our objects.</p>
<h3>Output:</h3>
<div id="output"></div>
JavaScript
var myAddrBookEntry = {
"fname": "Larry",
"lname": "Bouthillier",
"addr": "Rhode Island",
"email": "[email protected]",
"person-role": "instructor",
"getFullName": function () {
// keyword 'this' refers to enclosing context for this function
return this.fname + " " + this.lname;
},
// printMe method outputs useful info for this object
"printMe": function () {
return "This person is " + this.fname + " " + this.lname + " and lives in " + this.addr + " and can be reached at " + this.email;
}
}
// totally different kind of object, but it has a printMe method
var myCompanyEntry = {
"name": "Google",
"location": "Mountain View, CA",
"isPublic": true,
"symbol": "GOGL",
"products": ["Android", "Chrome", "Google Search", "Google Earth"],
"printMe": function () {
var out = "The company is " + this.name + " in " + this.location + ". "
if (this.isPublic) {
out += 'Our stock symbol is ' + this.symbol + ". "
}
if (this.products) {
out += "We are known for: <ul>";
for (var i = 0; i < this.products.length; i++) {
out += "<li>" + this.products[i] + "</li> ";
}
out += "</ul>";
}
return out;
}
}
// prints any object that has printMe capability
// (this is just what toString() does in most JS objects)
function printObject(obj) {
// First, test for the *existence of the property* printMe
// in the object
if (obj.printMe) {
var el = document.getElementById("output");
el.innerHTML += obj.printMe() + "<br><br>";
}
}
// Print both objects!
printObject(myAddrBookEntry);
printObject(myCompanyEntry);