【发布时间】:2018-05-01 01:41:52
【问题描述】:
显然,我是一个初学者,正在努力弄清楚基本的员工,所以请多多包涵!
我将所有这些文件(index.html、app.js 和 calc.js)都放在同一个文件夹中,它们的内容如下所示。
我有 2 个问题:
1: 为什么在文件 (app.js) 中,导入类 Calc 并创建它的新实例有效,而在文件 (calc.js) 中类似的过程不适用于 Test 类?
2:如何在 *.html 文件中使用“Calc”类?
注意:我在 mac OS 10.13 上使用 chrome (62.0.3202.94 (Official Build) (64-bit))
// app.js
import { Calc } from './calc.js';
class Test {
static hello() {
console.log("hello from class1");
}
}
let c = new Calc(); // this works!
console.log(c.sum(2, 3) + 1); // 6
export { Test };
和
// calc.js
import { Test } from "./app.js";
class Calc {
sum(a, b) {
return a + b;
}
}
let t = new Test(); // Uncaught ReferenceError: Test is not defined
t.hello();
export { Calc };
最后是 HTML 文件:
<html>
<head>
<meta charset="utf-8" />
<script src="./app.js" type="module"></script>
<script src="./calc.js" type="module"></script>
</head>
<body>
<h1>ES6</h1>
<script>
let c = new Calc();
// simulate input summation from two textboxes for example
console.log(c.sum(2, 1)); //Uncaught ReferenceError: Calc is not defined
</script>
</body>
</html>
【问题讨论】:
标签: javascript html class oop ecmascript-6