javascript - 导入类之间的关系

标签 javascript node.js class

好吧..所以我想明白了。但我想确保它不可能。

假设我有 3 个文件: index.js主文件,player.js播放器类文件,game.js游戏类文件。 主文件(索引)正在导入所有类。但是,我需要有在两个文件中创建游戏对象的选项 例子: index.js:

var game = require("./game.js");
var player = require("./player.js");
new player("player");
new game("game");

player.js:

module.exports = class Player {
    constructor(arg){
        console.log(arg);
        var asd=new game("ASD");/// <- the problem

    }
};

game.js:

module.exports = class Game {
    constructor(arg){
        console.log(arg);
    }
};

如何在 index.jsplayer.js 中调用 player 类中的 Game 而不需要游戏 我知道这会解决它,但是还有没有重复要求的另一种方法吗? (2 个要求,一个在 index.js 中,一个在 player.js 中)

最佳答案

index.js:

var player = require("./player.js");
var game = player.Game;
new player("player");
new game("game");

播放器.js:

var game = require("./game.js");
module.exports = class Player {
    constructor(arg){
        console.log(arg);
        var asd=new game("ASD");/// <- the problem

    }
};
modules.exports.Game = Game;

游戏.js:

module.exports = class Game {
    constructor(arg){
        console.log(arg);
    }
};

关于javascript - 导入类之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54111548/

相关文章:

javascript - Winform 应用程序与 Chrome 浏览器中的 Web UI 进行通信

javascript - 更新 firestore 文档中的字段

javascript - 类型错误 : Object #<Object> has no method 'Schema'

c++ - 2 "interconnected"C++ 类的内存管理

python - 在自定义 Python 类中覆盖默认方法的简单方法?

javascript - 您如何以编程方式告诉 HTML SELECT 下拉(例如,由于鼠标悬停)?

javascript - 清除后,localStorage 会记住以前的值

javascript - 无法让文本插件与 IE 中的 requirejs 一起使用

javascript - 通过socket发送和接收数据 : Node. JS服务器、Java客户端

java - Java中如何组合类