[英]How do I export data from An Object?
I am trying to export an object called coffeeTree from a file called Coffee_Tree.js into a js file called coffee.js so I can grab data from the object.我正在尝试将名为 CoffeeTree 的 object 从名为 Coffee_Tree.js 的文件导出到名为 coffee.js 的 js 文件中,这样我就可以从 object 中获取数据。 But, I keep getting this:
但是,我不断得到这个:
Uncaught ReferenceError: coffee is not defined at Coffee_Tree.js:2未捕获的 ReferenceError:咖啡未在 Coffee_Tree.js:2 中定义
This is the code I have so Far, I am still A js beginner, But I can't figure out what to do I changed the html type to module, but that didn't work.这是我到目前为止的代码,我仍然是一个 js 初学者,但我不知道该怎么办我将 html 类型更改为模块,但这没有用。 Here's my code so far:
到目前为止,这是我的代码:
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);
Again in the Console I just keep getting this error:再次在控制台中,我不断收到此错误:
Uncaught ReferenceError: coffee is not defined
at Coffee_Tree.js:2
You need to你需要
(1) use the proper variable name (either coffeeTree
or coffee
- pick one, don't use both) (1) 使用正确的变量名(
coffeeTree
或coffee
- 选择一个,不要同时使用)
(2) An expression exported as default does not get put into the current scope as an identifier. (2) 默认导出的表达式不会作为标识符放入当前的 scope 中。 You're currently implicitly creating a global variable and running in sloppy mode.
您当前正在隐式创建一个全局变量并在草率模式下运行。 One of the main purposes of having a module system is to avoid global variables when possible.
拥有模块系统的主要目的之一是尽可能避免使用全局变量。 Use named exports instead so that the object can reference itself inside its methods, and without assigning to the global object:
改用命名导出,以便 object 可以在其方法中引用自身,而无需分配给全局 object:
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);
(I'd also highly recommend using strict mode, if at all possible - if you read the error messages and try to debug them, it'll help you avoid these sorts of mistakes) (如果可能的话,我也强烈建议使用严格模式 - 如果您阅读错误消息并尝试调试它们,它将帮助您避免此类错误)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.