JavaScript: Accessing Private Variables
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...