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.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> </head> <body> <script type="text/javascript" src="PrivateMembers.js"></script> </body> </html>
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 += " " + 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 />");
© 20072024 XoaX.net LLC. All rights reserved.