闭包3
function myTool() { // 1. 私有的数据 var money = 1000; // 2. 提供操作私有变量的函数 function get() { money *= 10; console.log(money); } function send() { money--; console.log(money); } return { 'get': get, 'send': send }; } <script src="js/MyTool.js"></script> <script> var tool = myTool(); tool.get(); tool.send(); </script>
(function (w) { // 1. 私有的数据 var money = 1000; // 2. 提供操作私有变量的函数 function get() { money *= 10; console.log(money); } function send() { money--; console.log(money); } w.myTool = { 'get': get, 'send': send }; })(window);
高级排他
1 <script> 2 window.onload = function () { 3 var allLis = document.getElementsByTagName('li'); 4 // 记录移动前选中的里索引 5 var preSelectedIndex = 0; 6 for(var i=0; i<allLis.length; i++){ 7 var li = allLis[i]; 8 (function (i) { 9 li.onmouseover = function () { 10 // 清除之前的样式 11 allLis[preSelectedIndex].className = ''; 12 // 设置样式 13 this.className = 'current'; 14 // 更新 15 preSelectedIndex = i; 16 } 17 })(i); 18 } 19 } 20 </script>
函数节流
<script> /* var timer = null; window.onresize = function (ev) { clearTimeout(timer); timer = setTimeout(function () { console.log('大家好!'); }, 200); }; */ function throttle(fn, delay) { var timer = null; return function () { clearTimeout(timer); timer = setTimeout(fn, delay) } } window.onresize = throttle(function () { console.log('大家好!'); }, 200); window.onscroll = throttle(function () { console.log('大家好!!!!!!!!'); }, 200); </script>
<script> function fn1() { var arr = new Array(99999); function fn2() { console.log(arr); } return fn2; } var f = fn1(); f(); f = null; </script>
内存泄漏
1 // 内存溢出 2 /*var arrObj = {}; 3 for (var i = 0; i < 100000000; i++) { 4 arrObj[i] = new Array(99999999); 5 console.log(arrObj); 6 }*/
// 内存泄漏 /* var num = new Array(9999999); console.log(num); num = null;*/ 占用内存很大的全局变量,使用完就置为Null
1 内存泄漏 2 // 定时器 3 /* setInterval(function () { 4 console.log('----------------------'); 5 }, 1000);*/