Public
--------------------------------------------------------------------------------------------------------------------
1.
function PublicCats() {
2.
// This is the list of cat names
3.
this.nameList = [];
4.
5.
// This is a method that I would like to be private but can’t
6.
// It returns the last cat of the list
7.
this.lastCat = function() {
8.
return this.nameList[this.nameList.length-1];
9.
}
10.
11.
// Return the list of names
12.
this.names = function() {
13.
return this.nameList;
14.
}
15.
16.
// Add a name to the list
17.
this.add = function(name) {
18.
this.nameList.push(name);
19.
20.
// Return the last cat just added
21.
return this.lastCat();
22.
}
23.
}
private:
-------------------------------------------------------------------------------------------------------------
1.
function PrivateCats() {
2.
// This is the list of cat names
3.
var nameList = [];
4.
5.
// This is a private method
6.
var lastCat = function() {
7.
// Note : I don’t use "this" to access private variables
8.
// thanks to the power of closures!
9.
return nameList[nameList.length-1];
10.
}
11.
12.
// These are our public methods!
13.
// This is where we create another scope to
14.
// avoid external objects to use the private variables.
15.
return {
16.
add:function(name) {
17.
// Note : once again, I don’t use "this"
18.
// to access the private variables and methods
19.
nameList.push(name);
20.
return lastCat();
21.
},
22.
names:function() {
23.
return nameList;
24.
}
25.
}
26.
}