<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 防止变量泄露
私有属性
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