[英]Nested functions error, Unexpected token ':', Cannot read property of undefined
I want to make my code more clear, that the reason i am trying to learn namespaces or nested functions.我想让我的代码更清楚,这是我尝试学习命名空间或嵌套函数的原因。 I've read about them in several places and as i understood
'Revealing Module'
is the best option.我在几个地方读过它们,据我所知,
'Revealing Module'
是最好的选择。 So i tried to copy second example from this post namespace .所以我试图从这个帖子命名空间复制第二个例子。
At first, i got the error when trying to return object with two methods: Unexpected token ':'
.起初,我在尝试使用两种方法返回 object 时遇到错误:
Unexpected token ':'
。 When i tried to return one method instead of 2, i got the Cannot read property of undefined
error when tried to call applyEvents
of expandableElements
object.当我尝试返回一个方法而不是 2 时,在尝试调用
expandableElements
元素applyEvents
的 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'
The return
and the JSON must be on the same line. return
和 JSON 必须在同一行。 As soon as the return line is executed, the control is handed over to the caller (with undefined
) and the JSON line never get executed.一旦执行返回行,控制权就会移交给调用者(使用
undefined
),并且 JSON 行永远不会被执行。
do it like this:像这样做:
...
return {
applyEvents : applyExpandEvents,
closeAll : closeAllExpands // Unexpected token ':'
};
Detailed Explanation from MDN docs about return : MDN 文档中关于 return的详细说明:
The return statement is affected by automatic semicolon insertion (ASI).
return 语句受自动分号插入 (ASI) 的影响。 No line terminator is allowed between the return keyword and the expression.
return 关键字和表达式之间不允许有行终止符。
return
a + b;
is transformed by ASI into:由 ASI 转化为:
return;
a + b;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.