【发布时间】:2020-10-03 01:43:58
【问题描述】:
我想让我的代码更清晰,这是我尝试学习命名空间或嵌套函数的原因。我在几个地方读过它们,据我所知'Revealing Module' 是最好的选择。所以我试图从这篇文章namespace复制第二个例子。
起初,我在尝试使用两种方法返回对象时遇到错误:Unexpected token ':'。当我尝试返回一种方法而不是 2 时,尝试调用 expandableElements 对象的 applyEvents 时出现 Cannot read property of undefined 错误。
let expandableElements =
(
function()
{
// All expandable elements
let expands = document.querySelectorAll(".expand-icon");
// Apply events to all .expand-icon elements
function applyExpandEvents()
{
for(let i = 0; i < expands.length; i++)
{
expands[i].addEventListener("click", expandList);
}
// Expand method
function expandList()
{
this.classList.toggle("active");
let content = this.previousElementSibling;
if (content.style.maxHeight)
{
content.style.padding = "0";
content.style.maxHeight = null;
}
else
{
content.style.padding = "1rem";
content.style.paddingBottom = "0.5rem";
content.style.maxHeight = content.scrollHeight + 20 + "px";
}
}
}
// Close all expanded lists
function closeAllExpands()
{
for(let i = 0; i < expands.length; i++)
{
let expand = expands[i];
if(expand.classList.contains("active"))
{
expand.classList.toggle("active");
expand.previousSibling.style.padding = "0";
expand.previousSibling.style.maxHeight = null;
}
}
}
return
{
applyEvents : applyExpandEvents,
closeAll : closeAllExpands // Unexpected token ':'
};
}
)();
expandableElements.applyEvents(); // If remove closeAll from return, then'Cannot read property applyEvents of undefined'
【问题讨论】:
标签: javascript namespaces nested-function javascript-namespaces