作用域控制变量的可见范围。

JavaScript: The Good Parts

Instead of initializing myObject with an object literal, we will initialize myObject by calling a function that returns an object literal. That function defines a value variable. That variable is always available to the increment and getValue methods, but the function's scope keeps it hidden from the rest of the program



1 <script type="text/javascript">
2 var wObject = function () {
3 var value = 0;
4 return {
5 increment: function (inc) {
6 value += typeof inc === 'number' ? inc : 1;
7 },
8 getValue: function () {
9 return value;
10 }
11 }
12 }();
13 wf(wObject)
14 function wf(w) {
15 console.log(w)
16 }
17
18 wf(wObject.increment(3))
19 wf(wObject.getValue())
20 wf(wObject.increment(3))
21 wf(wObject.getValue())
22
23 var wObject = function () {
24 var value = 0;
25 return {
26 increment: function (inc) {
27 value += typeof inc === 'number' ? inc : 1;
28 return 'www';
29 },
30 getValue: function () {
31 return value;
32 }
33 }
34 }();
35 wf(wObject)
36 function wf(w) {
37 console.log(w)
38 }
39
40 wf(wObject.increment(3))
41 wf(wObject.getValue())
42 wf(wObject.increment(3))
43 wf(wObject.getValue())
44 </script>


 

initialize myObject by calling a function that returns an object literal_javascript

 

initialize myObject by calling a function that returns an object literal_控制变量_02