-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprivate-vars.html
81 lines (75 loc) · 2.5 KB
/
private-vars.html
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
77
78
79
80
81
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>private vars in JS</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
// Using jQuery as $
$(function(){ // run when document loaded
var NS = {}; // some namespace, see? Has little to do with anything…
(function(){
// Private vars
var somelist = ['Emily', 'Chelsey', 'Sarah', 'Rachel'];
NS.people = {
addPerson: function (name) {
somelist.push(name);
},
listPeople: function() {
return somelist.join(', ')+'.';
}
};
})();
var $o = $('#output');
$o.append($('<li />').text('Initial list: '+NS.people.listPeople()));
$o.append($('<li />').text('(Adding Kelley…)'));
NS.people.addPerson('Kelley');
$o.append($('<li />').text('Now list is: '+NS.people.listPeople()));
$o.append($('<li />').text('Can we access `somelist`? No, but let’s try:'));
try {
$o.append($('<li />').text('NS.people.somelist: '+NS.people.somelist +
'; window.somelist: '+window.somelist
));
} catch (e) {
$o.append($('<li />').text(''+e));
}
});
</script>
</head>
<body>
<h1>private vars in JS</h1>
<p>See <a href="http://www.crockford.com/javascript/private.html">Crockford’s piece</a>. I think this demo is a hell of a lot simpler / easier to follow though, if you know anything about JavaScript variable scope & closures.</p>
<pre><code class="js">
// Using jQuery as $
$(function(){ // run when document loaded
var NS = {}; // some pseudo-namespace, see? Has little to do with anything…
(function(){
// Private vars
var somelist = ['Emily', 'Chelsey', 'Sarah', 'Rachel'];
NS.people = {
addPerson: function (name) {
somelist.push(name);
},
listPeople: function() {
return somelist.join(', ')+'.';
}
};
})();
var $o = $('#output');
$o.append($('<li />').text('Initial list: '+NS.people.listPeople()));
$o.append($('<li />').text('(Adding Kelley…)'));
NS.people.addPerson('Kelley');
$o.append($('<li />').text('Now list is: '+NS.people.listPeople()));
$o.append($('<li />').text('Can we access `somelist`? No, but let’s try:'));
try {
$o.append($('<li />').text('NS.people.somelist: '+NS.people.somelist +
'; window.somelist: '+window.somelist
));
} catch (e) {
$o.append($('<li />').text(''+e));
}
});
</code></pre>
<div id="output"></div>
</body>
</html>