* 一个对象池的简单应用 tool tip
tootip.html
<html> <head> <meta charset="UTF-8"> <title>tool tip</title> </head> <body> <script type="text/javascript" src="js/toolTip.js"></script> </body> </html>
js/toolTip.js
var toolTipFactory = (function() { var toolTipPool = []; return { create: function() { if (toolTipPool.length === 0) { var div = document.createElement("div"); document.body.appendChild(div); console.log("div created"); return div; } else { return toolTipPool.shift(); } }, recover: function(toolTipDom) { return toolTipPool.push(toolTipDom); } } })(); var a = []; for (var i = 0, str; str = [‘A‘, ‘B‘][i]; i++) { var toolTip = toolTipFactory.create(); toolTip.innerHTML = str; a.push(toolTip); } // 回收进对象池 a.forEach(function(toolTip) { toolTipFactory.recover(toolTip); }); // 再创建6个小气泡 setTimeout(function() { [‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘].forEach(function(str) { var toolTip = toolTipFactory.create(); toolTip.innerHTML = str; }); }, 500);
Run:
php -S 0.0.0.0:9000
A, B没有重复创建
* 通用对象池的实现
iframe.html
<html> <head> <meta charset="UTF-8"> <title>通用对象池 创建iframe测试</title> </head> <body> <script src="./js/iframe.js"></script> </body> </html>
js/iframe.js
var objectPoolFactory = function(createObjFn) { var objectPool = []; return { create: function() { var obj = objectPool.length === 0 ? createObjFn.apply(this, arguments) : objectPool.shift(); return obj; }, recover: function(obj) { objectPool.push(obj); } } }; // test var iframeFactory = objectPoolFactory(function() { var iframe = document.createElement(‘iframe‘); document.body.appendChild(iframe); iframe.onload = function() { iframe.onload = null; // 防止iframe重复加载 iframeFactory.recover(iframe); // iframe加载完了回收节点 } return iframe; }); var iframe1 = iframeFactory.create(); iframe1.src = ‘https://www.baidu.com‘; var iframe2 = iframeFactory.create(); iframe2.src = ‘http://www.qq.com/‘; setTimeout(function() { var iframe3 = iframeFactory.create(); iframe3.src = ‘http://www.163.com‘; }, 750);
Run:
原文地址:https://www.cnblogs.com/mingzhanghui/p/9397246.html
时间: 2024-11-10 16:15:18