我有一个文件class.js
//implementation details
const _stackCollection = new WeakMap();
//interface
export class Stack {
constructor() {
_stackCollection.set(this, []);
}
get count() {
return _stackCollection.get(this).length;
}
pop() {
if (this.count === 0)
throw new Error('Nothing to pop');
return _stackCollection.get(this).pop();
}
peek() {
if (this.count === 0)
throw new Error('Nothing to peek');
return _stackCollection.get(this)[this.count - 1];
}
push(e) {
_stackCollection.get(this).push(e);
return;
}
}
导入给定类的模块如下所示 模块.js:
import {Stack} from './class.js';
index.html 看起来像这样:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>hello world</h1>
<script type="module" src='module.js'></script>
</body>
</html>
当我尝试在控制台中初始化 Stack 实例时,出现以下错误。关于给定的错误有很多问题,但我看不出有什么可以帮助我的:
const stack=new Stack()
Uncaught ReferenceError: Stack is not defined
at <anonymous>:1:13
最佳答案
模块中的声明仅限于该模块。如果要访问它们,则需要导入它们。
要在浏览器控制台中使用这样的导出,您需要将其导入或将其绑定(bind)到全局变量。
全局(请注意,这违背了模块的目的,只能用于临时测试)
export class A {}
// TODO: remove this
window.A = A;
使用建议的动态导入语法:
// browser console:
import('./a.js').then(console.log);
使用 SystemJS
// browser console:
SystemJS.import('./a.js').then(console.log);
关于javascript - 从浏览器控制台 JS 调用类(在模块中定义)时,'Uncaught ReferenceError : . .. 未定义',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51986073/