嵌套函数错误,意外标记“:”,无法读取未定义的 属性

Nested functions error, Unexpected token ':', Cannot read property of undefined

我想让我的代码更清晰,这就是我尝试学习命名空间或嵌套函数的原因。我在几个地方读到过它们,据我所知,'Revealing Module' 是最好的选择。所以我试图从这个 post namespace.

复制第二个例子

起初,我在尝试使用两种方法 return 对象时遇到错误:Unexpected token ':'。当我尝试 return 一种方法而不是 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'

return和JSON必须在同一行。一旦执行了 return 行,控制权就会移交给调用者(使用 undefined)并且永远不会执行 JSON 行。

这样做:

...
        return {
            applyEvents : applyExpandEvents,
            closeAll    : closeAllExpands // Unexpected token ':'
        };

详细说明 来自 MDN docs about return:

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

return
a + b;

被ASI转化为:

return; 
a + b;