Core JavaScript

Private Members

Unlke most object-oriented languages, JavaScript does not allow a programmer to declare variables as private. However, similar functionality can be accomplished by declaring a variable in the constructor function without using this before it; be sure to use 'var' to ensure that the variable is not a global. We demonstrate this in the code below, where we access this variable from the member function.

PrivateMembers.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="PrivateMembers.js"></script>
</body>
</html>

PrivateMembers.js

function CPerson(sName, iAge) {
  // public
  this.msName = sName;
  // private - declare with 'var'
  var miAge = iAge;
  // These functions can access miAge. They must be declared inside the constructor.
  this.fnGetAge = function() {
    return miAge;
  }
  this.fnAdvanceAge = function() {
    ++miAge;
  }
}

// This function just prints out the members of an object.
function PrintAnObject(qObject) {
  var sOutput = typeof(qObject)+": " + qObject.constructor.name + '<br />';
  for (var sProperty in qObject) {
    sOutput += "&nbsp;&nbsp;&nbsp;&nbsp;" + sProperty + ': ' + qObject[sProperty]+'<br />';
  }
  document.writeln(sOutput + "<br />");
}

var qJesus = new CPerson("Jesus", 30);
PrintAnObject(qJesus);

document.writeln(qJesus.msName + "' age is " + qJesus.fnGetAge() + "<br />");
qJesus.fnAdvanceAge();
document.writeln(qJesus.msName + "' age is " + qJesus.fnGetAge() + "<br />");
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.