首页 > 其他 > 详细

initialize myObject by calling a function that returns an object literal

时间:2017-02-13 08:19:41      阅读:162      评论:0      收藏:0      [点我收藏+]

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

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

原文:http://www.cnblogs.com/yuanjiangw/p/6392220.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!