【问题标题】:Nested functions error, Unexpected token ':', Cannot read property of undefined嵌套函数错误,意外标记“:”,无法读取未定义的属性
【发布时间】: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


    【解决方案1】:

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

    这样做:

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

    详解来自MDN docs about return

    return 语句受自动分号插入 (ASI) 的影响。 return 关键字和表达式之间不允许有行终止符。

    return
    a + b;
    

    被 ASI 转化为:

    return; 
    a + b;
    

    【讨论】:

    • 什么鬼哈哈?))我不喜欢当第一个大括号在同一行时,为什么这甚至是一个问题?))
    • 我已经解释了原因。请看一下
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2020-10-15
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多