public
Description: Examples for javascriptkata.com
Homepage: http://www.javascriptkata.com
Clone URL: git://github.com/dsimard/jskata_examples.git
dsimard (author)
Mon Oct 05 07:36:30 -0700 2009
commit  a4240da8d85d09a1f8891eef172e486367fe3da9
tree    7ce974aa97627afd9af5676d69409085e87e5ef6
parent  1719f0731a14cf252565fe20315cc4e3b300f0bf
jskata_examples / private / private.js
100644 76 lines (64 sloc) 1.968 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// When the page is loaded
function load() {
var pubCats = new PublicCats();
var privCats = new PrivateCats();
 
var log = function log(msg) {
if (typeof msg == "object" && msg.length) msg = msg.join("");
$("body").append($("<div>").html(msg));
}
 
// Adding a cat is the same
pubCats.add("Mistigri");
pubCats.add("Felix");
privCats.add("Mimi");
privCats.add("Duchess");
jsKataEx.assert(pubCats.names().length == 2, "pubCats has 2 cats");
jsKataEx.assert(privCats.names().length == 2, "privCats has 2 cats");
 
// Check scopes
jsKataEx.assert(pubCats.nameList, " : I CAN access the private nameList variable from public cats");
jsKataEx.assert(privCats.nameList, " : I CANNOT access the nameList variable from private cats");
}
 
// This class uses public variables
function PublicCats() {
// This is the list of cat names
this.nameList = [];
 
// This is a method that I would like to be private but can't
// It returns the last cat of the list
this.lastCat = function() {
return this.nameList[this.nameList.length-1];
}
 
// Return the list of names
this.names = function() {
return this.nameList;
}
 
// Add a name to the list
this.add = function(name) {
this.nameList.push(name);
 
// Return the last cat just added
return this.lastCat();
}
}
 
// This class uses private variables
function PrivateCats() {
// This is the list of cat names
var nameList = [];
 
// This is a private method
var lastCat = function() {
// Note : I don't use "this" to access private variables
// thanks to the power of closures!
return nameList[nameList.length-1];
}
 
// These are our public methods!
// This is where we create another scope to
// avoid external objects to use the private variables.
return {
add:function(name) {
// Note : once again, I don't use "this"
// to access the private variables and methods
nameList.push(name);
return lastCat();
},
names:function() {
return nameList;
}
}
}