标签:
<script type="text/javascript"> // 在匿名函数中使用var关键字 (function(){ var privateField = 42; function innerFunc(){ notSoPrivate =43; return notSoPrivate; } alert(privateField); // 42 privateField = innerFunc(); // alert(notSoPrivate); // 43 })(); alert(typeof privateField); // undefined alert(notSoPrivate); // 43 变量泄露 </script>
var obj =(function (){ var privateField = 42; var publicField = "foobar"; function processInternals(){ alert(‘Internal stuff : ‘ + privateField); } function run(){ processInternals(); alert(‘still private stuff : ‘ + privateField); alert(‘Public stuff : ‘ + publicField); } return { publicField : publicField, run : run }; })(); obj.run(); // 弹出 internal, still private, pupublic alert(obj.publicField); // foobar alert(obj.processInternals()); // Undefined alert(obj.privateField); // undefined
标签:
原文地址:http://www.cnblogs.com/tangruixin/p/4198915.html