js0013

封装私有变量

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
<!DOCTYPE html>
<html>

<head>
<title>Using closures to approximate private variable</title>
<meta charset="utf-8">
<script src="../assert.js"></script>
<link rel="stylesheet" type="text/css" href="../assert.css">
</head>

<body>
<script>
function Ninja() {
var feints = 0;
this.getFeints = function(){
return feints;
};
this.feint = function(){
feints++;
};
}

var ninja1 = new Ninja();
ninja1.feint();

assert(ninja1.feints === undefined,
"And the private data is inaccessible to us.");
assert(ninja1.getFeints() === 1,
"We're able to access the internal feint count.");


var ninja2 = new Ninja();
assert(ninja2.getFeints() === 0,
"The second ninja object gets it’s own feints variable.");
</script>
</body>
</html>