【问题标题】:Why can I access const before declaration in exported module为什么我可以在导出模块中声明之前访问 const
【发布时间】:2020-07-20 13:35:57
【问题描述】:

我有这个问题,因为 const 变量没有被提升并且应该抛出一个语法错误。

为什么这段代码有效?

export let testModule = () => {
    let test = document.querySelector('.test');
    test.innerHTML = myText;
    test.style.cssText = 'color: red';
}

const myText = 'IT WORKS!!!!!'

如果您想自己检查,我已附上工作插件:https://plnkr.co/edit/TR8SvCjQgqPDWpI3?preview

【问题讨论】:

    标签: ecmascript-6 import module export hoisting


    【解决方案1】:

    为什么我可以在导出模块中声明之前访问 const

    因为 testModule() 直到稍后才会被调用,而 const myText 在函数被调用时被定义在一个可达范围内。

    【讨论】:

    • 很好的答案!我在与一些同事交谈时也意识到了这一点,但想仔细检查一下。
    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2020-09-29
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多