我正在尝试在单独的 javascript 文件中定义一个类,然后在我的 HTML 文件中使用该类。
这就是我正在尝试的。
- 我在 VoiceCard.js 文件中创建类 VoiceCard:
class VoiceCard {
constructor(nickname, date_time, post_title, voice_post) {
this.nickname = nickname;
this.date_time = date_time;
this.post_title = post_title;
this.voice_post = voice_post;
}
- 我创建了一个 HTML 文件,在其中将文件添加为源:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script type="module" src="../VoiceCard.js"></script>
</head>
- 我创建了一个脚本,在其中调用类以创建 VoiceCard 类的新变量并将其中一个属性记录到控制台:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script type="module" src="../VoiceCard.js"></script>
</head>
<body>
<script type="text/javascript">
let v_card = new VoiceCard(
"Lorder",
"12:00",
"First Voicer Post",
"file_location.mp4");
console.log(v_card.nickname);
</script>
</body>
</html>
错误是:未捕获 ReferenceError:未定义语音卡。
我似乎找不到错误的原因。任何帮助,将不胜感激。
回答1
模块不创建全局变量。这是他们的重点。 :-)
以下是如何执行您似乎想要执行的操作:
删除
VoiceCard.js
的script
标签。在
VoiceCard.js
中,通过在class
前面添加export
来导出类。将您的内联脚本更改为从
VoiceCard.js
文件导入类的内联模块。
所以:
export class VoiceCard {
// ^^^
constructor(nickname, date_time, post_title, voice_post) {
this.nickname = nickname;
this.date_time = date_time;
this.post_title = post_title;
this.voice_post = voice_post;
}
} // <== This closing `}` was missing
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<!-- No script tag for VoiceCard -->
</head>
<body>
<script type="module">
import { VoiceCard } from "../VoiceCard.js"; // ***
let v_card = new VoiceCard(
"Lorder",
"12:00",
"First Voicer Post",
"file_location.mp4"
);
console.log(v_card.nickname);
</script>
</body>
</html>
浏览器在看到 import
时会自动下载 VoiceCard.js
。
回答2
您可以删除 type="module"
来解决此问题
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
<script src="../VoiceCard.js"></script>
</head>
<body>
<script type="text/javascript">
let v_card = new VoiceCard(
"Lorder",
"12:00",
"First Voicer Post",
"file_location.mp4");
console.log(v_card.nickname);
</script>
</body>
</html>