webpack环境下多个import引入的类如何互相调用彼此的方法?
问题原因
你遇到的报错本质是模块作用域隔离导致的:
- webpack打包时每个js文件都是独立的模块,你在index.js顶层声明的
GAME、LAND是仅属于index.js模块的局部变量,其他模块(比如GameController所在的文件)默认无法直接访问 - 原生JS能正常运行是因为你把变量写在了全局作用域,默认挂载到
window对象,所有脚本都能直接读取全局对象的属性
推荐解决方案:依赖注入
这是耦合度最低、可维护性最高的方案,直接在实例化类的时候把需要的外部实例传入:
首先修改GameController类代码:
export default class GameController { tickCount = 0; // 新增constructor接收传入的LandController实例 constructor(landInstance) { this.land = landInstance; } tick = setInterval( () => { this.Tick() }, 1000); Tick () { // 用实例上挂载的land对象调用方法 this.land.updateLand(); this.tickCount++; } }
然后修改index.js的实例化逻辑,把LAND实例传入GameController:
import GameController from './Controllers/GameController' import LandController from './Controllers/LandController' const LAND = new LandController(); // 实例化时把LAND传入 const GAME = new GameController(LAND);
其他可选方案
- 全局挂载(不推荐,会污染全局作用域)
在index.js里实例化后把对象挂载到window:
const LAND = new LandController(); const GAME = new GameController(); window.LAND = LAND; window.GAME = GAME;
之后在任意模块都可以直接通过window.LAND、window.GAME访问实例。
- 统一导出实例
新增一个instances.js文件统一管理全局实例,避免循环导入问题:
// instances.js export let GAME = null; export let LAND = null; export function setInstances(game, land) { GAME = game; LAND = land; }
然后在index.js里实例化后调用赋值:
import { setInstances } from './instances.js' import GameController from './Controllers/GameController' import LandController from './Controllers/LandController' const GAME = new GameController(); const LAND = new LandController(); setInstances(GAME, LAND);
需要用的地方直接导入对应实例即可:
// GameController.js import { LAND } from '../instances.js' // 后续Tick方法里直接用LAND即可
内容的提问来源于stack exchange,提问作者Aaranihlus
相关产品推荐
相关产品推荐

