Private Properties in a Constructor Function
for CSCI E3, Harvard University author(s): Larry Bouthillier
by DustyWhite
HTML
<div>
<p>Notice that on Line 3, we've declared a property using the standard <i>var</i> keyword rather than using <i>this</i>. </p>
<p>Inside a constructor function, declared functions and variables are private - they are inaccessable from outside. They follow the normal rules of variable scope inside a function that we learned in Week 5. </p>
<p>In this example, we're setting personRole when we call the object's constructor, and there's no way to change it afterwards.</p>
<p>On line 27, we appear to be setting personRole. What we're really doing is making a new, public property called personRole. It's entirely unrelated to the personRole variable and doesn't affect the getPersonRole() method. </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, r) {
var personRole = r;
this.fname = f;
this.lname = l;
this.addr = a;
this.email = e;
this.getFullName = function(){
return this.fname + " " + this.lname;
}
this.getPersonRole = function(){
return personRole;
}
}
// Create an object using the constructor
var you = new AddrBookEntry("Excellent","Student","Cambridge","[email protected]", "student");
// Call on the objects' properties and methods
logMessage(you.fname); // Excellent
logMessage(you.personRole); // private, and therefore undefined
logMessage(you.getPersonRole()); // student
// Now let's have some fun
you.personRole = "jester"; // this creates a new property, personRole
logMessage(you.personRole); // we can access this property
logMessage(you.getPersonRole());// but the private variable is still 'student'
// Utility function for logging convenience
// Logs 'msg' to the element with provided 'id'
// If 'id' is undefined, logs to #output
function logMessage(msg, id){
if (!id){
id="output";
}
document.getElementById(id).innerHTML += msg + "<br>";
}