<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);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.