gpt4 book ai didi

javascript - 箭头函数不适用于模块?

转载 作者:行者123 更新时间:2023-12-01 00:51:43 25 4
gpt4 key购买 nike

所以我正在练习我的 JavaScript 技能。我目前正在学习 es6,并尝试将箭头函数与模块一起使用,但它们似乎不能一起工作。这是什么原因?

我尝试过只使用一个 JavaScript 文件。当 HTML 中的脚本类型属性为“text/javascript”时,箭头函数可以工作,但我想将代码分开,以便更清晰、更易于管理。所以我使用了模块。我将脚本类型属性设置为“模块”,这样就可以了。但现在我已经分离了代码,箭头函数将不再起作用。

<小时/>

无模块

<小时/>

HTML

    <script type="text/javascript" src="script.js" async></script>

Javascript

    const quoteBtn = document.getElementById('quoteBtn');
const quote = document.getElementById('quote');
const author = document.getElementById('author');

const quotes = [
{name:'Stephen King', quote:'signosfnggf'}
/// more objects...
]

displayQuote =()=> {
var selectQuote = Math.floor(Math.random() * quotes.length);
quote.innerHTML = `"${quotes[selectQuote].quote}"`;
author.innerHTML = `<i> - ${quotes[selectQuote].author}</i>`;
}

quoteBtn.addEventListener('click', displayQuote);
<小时/>

带模块

<小时/>

HTML

    <!-- Module type required in using module functionality-->
<script type="module" src="script.js" async></script>

JS(现在使用模块...)


import {quotes} from './lib/quotes.js'
const quoteBtn = document.getElementById('quoteBtn');
const quote = document.getElementById('quote');
const author = document.getElementById('author');

displayQuote =()=> { /*Uncaught ReferenceError: displayQuote is not
defined*/

var selectQuote = Math.floor(Math.random() * quotes.length);
quote.innerHTML = `"${quotes[selectQuote].quote}"`;
author.innerHTML = `<i> - ${quotes[selectQuote].author}</i>`;
}

quoteBtn.addEventListener('click', displayQuote);

我希望箭头函数能够与模块一起使用并正常运行。但浏览器给我一个错误:script.js:6 Uncaught ReferenceError :displayQuote 未定义

最佳答案

您需要添加 letvarconst - 我会使用 const 因为它是一个函数:

const displayQuote = () => {...}

声明不带这些关键字的变量会导致 implicit global ,并且在严格模式下失败。

关于javascript - 箭头函数不适用于模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56920572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com