about


Scribe:

chrono

blog

Time

science!

book musings

gov

'punk

missle defense

jams

antiques

cultcha blog


Construct:

scripts & programs

on the town

snaps


Self:

creds (PDF)

key

missive


JavaScript: Accessing Private Variables

Variables can be kept private, or not made accessible, within an object constructor, namely by using the "var" keyword instead of the "this"...
function Song(name, year, timesPlayedThusFar) {
  this.name = name;
  this.yearRecorded = year;
  var timesPlayed = timesPlayedThusFar;
}
In the object constructor above, the name and yearRecorded variables can be accessed by calls outside the object, though timesPlayed may not.

In order to allow access a private variable, you can define a public method from within the constructor:

function Song(name, year, timesPlayedThusFar) {
  this.name = name;
  this.yearRecorded = year;
  var timesPlayed = timesPlayedThusFar;
  
  this.TimesSongPlayed = function() {
      return(timesPlayed);
   };
  
}
In the case, calling the TimesSongPlayed returns the timesPlayed variable. Here is an example of how to use a public method to call a private variable...

Back to the JavaScript Page
.