javascript - 如何从对象中导出数据?
问题描述
我正在尝试将名为 CoffeeTree 的对象从名为 Coffee_Tree.js 的文件导出到名为 coffee.js 的 js 文件中,以便从该对象中获取数据。但是,我不断得到这个:
未捕获的 ReferenceError:咖啡未在 Coffee_Tree.js:2 中定义
这是我到目前为止的代码,我仍然是一个 js 初学者,但我不知道该怎么做我将 html 类型更改为模块,但这没有用。到目前为止,这是我的代码:
Coffee_Tree.js
export default coffeeTree = {
refill: () => {
coffee.isEmpty = false;
console.log('refilled');
},
drink: () => {
coffee.isEmpty = true;
console.log('chug');
},
isEmpty: true,
}
coffee.js
import coffeeTree from './Coffee_Tree.js';
console.log(coffeeTree);
再次在控制台中,我不断收到此错误:
Uncaught ReferenceError: coffee is not defined
at Coffee_Tree.js:2
解决方案
你需要
(1) 使用正确的变量名(coffeeTree
或者coffee
- 选择一个,不要同时使用)
(2) 默认导出的表达式不会作为标识符放入当前范围。您当前正在隐式创建一个全局变量并在草率模式下运行。拥有模块系统的主要目的之一是尽可能避免使用全局变量。改为使用命名导出,以便对象可以在其方法中引用自身,而无需分配给全局对象:
export const coffee = {
refill: () => {
coffee.isEmpty = false;
console.log('refilled');
},
drink: () => {
coffee.isEmpty = true;
console.log('chug');
},
isEmpty: true,
};
import { coffee } from './Coffee_Tree.js';
console.log(coffee);
(如果可能的话,我也强烈建议使用严格模式 - 如果您阅读错误消息并尝试调试它们,它将帮助您避免此类错误)
推荐阅读
- css - CSS nth-chid 选择器没有隐藏的冷节点
- python - tkinter中的PNG图像透明度
- node.js - Electron App 打包后没有运行
- python-3.x - pyautogui 不在文本字段中写入 Excel 单元格内容
- python - 我似乎无法在 python 3 中找到数字的最高素数的正确代码
- javafx - 在按钮上显示“stage2”后如何隐藏“stage1”单击[JavaFX]
- laravel - Laravel 在路由中使用数据库变量
- java - Apache Pulsar:订阅时检查/获取分区元数据时出错
- asp.net - 如何在asp.net mvc的url中添加页面标题?
- django - pipenv 不在 ubuntu 19.04 中安装 django