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. But, I keep getting this:
Uncaught ReferenceError: coffee is not defined at 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. 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)
(2) An expression exported as default does not get put into the current scope as an identifier. 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:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.