我正在开发一个用于创建 UI 组件的自定义 js 库,我想知道(并理解)以下两种方法的影响:
(下面的代码只是为了展示概念)
第一种方法是封装元素:
function wrapElement(id) {
var el = document.getElementById(id);
return {
el:el,
hide:function() {
// set el.style.display to 'none'
},
show:function() {
// set el.style.display to ''
},
getSize:function() {
// get the size of the el
}
}
}
var myEl = wrapElement('abc');
myEl.hide();
第二种方法是通过实用程序类来操作元素:
var ElementUtil = {
get:function(id) {
return document.getElementById(id);
},
hide:function(el) {
// set the el.style.display to 'none'
},
show:function(el) {
// set the el.style.display to ''
},
getSize:function(el) {
// get the size of the el
}
}
var myEl = ElementUtil.get('abc');
ElementUtil.hide(myEl);
如果考虑内存消耗和性能,上面哪一个更好?
(请注意:我不想使用像 jQuery 这样的现有库)
非常感谢任何建议或指示。
最佳答案
第一个解决方案将占用更多内存。每次包装一个对象时,都会创建一个指向元素“el”的额外指针以及 3 个函数。每次包装 ID 时,您都会创建这些函数。
第二种解决方案仅创建函数一次,并将指向元素的指针返回给调用者,因此您可以节省更多内存和时间。
关于javascript - 包装 DOM 元素或使用实用程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21656840/