首页 > 解决方案 > 如何从对象中导出数据?

问题描述

我正在尝试将名为 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

标签: javascriptobject

解决方案


你需要

(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);

(如果可能的话,我也强烈建议使用严格模式 - 如果您阅读错误消息并尝试调试它们,它将帮助您避免此类错误)


推荐阅读