所以我正在练习我的JavaScript技能。我目前正在研究ES6,但我正在尝试使用模块的箭头功能,但它们似乎并没有合作。这样做的原因是什么?
我仅尝试使用一个JavaScript文件。当html中的脚本类型属性为"文本/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未介绍的参考文献:displayQuote未定义
您需要添加let
,var
或const
-我会使用const
,因为它是一个函数:
const displayQuote = () => {...}
在没有这些关键字的情况下声明变量会导致隐式全局,并且在严格的模式下失败。