Public / Private Variables and Methods in JavaScript

Every time I want to write some Object Oriented code whether it be PHP or JavaScript I require a slight mental jump start to remember each language’s syntax, but hopefully with enough repetition I’ll start differentiating and remembering the syntax.

I ran across a really nice article at phrogz.net

Object Layout

function Player(name) {
var name; // private variable
var age = 0; // private variable
var SetName = function(newName) { name = newName; } // private method

function SetAge(newAge) { age = newAge; } // private method
this.GetAge = function() { return age; } // privileged method
this.friend = "nobody"; // public variable - declared internally

SetName(name); // redundant mutator, but an example of calling a private method
this.constructor.count++; // increase the static count variable
}
Person.count = 0; // static variable
Person.prototype.goldStars = 0; // public property declared externally

Private Variables and Methods
Must be declared within the object. Only privileged methods can view/edit/invoke.

var name;  // private variable
var age = 0; // private variable
var SetName = function(newName) { name = newName; } // private method
function SetAge(newAge) { age = newAge; } // private method

Privileged Methods
Publically accessible, declared within the object, cannot be changed, but can be replaced publically “overridden”

this.GetAge = function() { return age; }

Public Variables and Methods
Can be declared within the object or externally

this.friend = "nobody"; // declared internally, cant be changed, but can be replaced publically "overridden"
Person.prototype.goldStars = 0; // declared externally, can be changed
Person.prototype.AddGoldStar = function() { this.goldStars++; }  // declared externally, can be changed

Static Properties and Methods
Always public, anyone can read/write

Person.count = 0;
Person.FindAll = function() { return $(".person"); } // simple jquery example for a static method
Person .FindIndividual = function(name) { return $(".person[person="+name+"]"); }

This entry was posted in Interesting Finds and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Leave your thoughts...

You must be logged in to post a comment.