Javascript 从一个导入到另一个的类关系

Javascript 从一个导入到另一个的类关系,javascript,node.js,class,Javascript,Node.js,Class,好吧,我算是明白了。但我想确定这是不可能的 假设我有3个文件: index.jsmain文件,player.jsplayer类文件,game.jsgame类文件。 主文件(索引)正在导入所有类。但是,我需要有在两个文件中创建游戏对象的选项 例子: index.js: var game = require("./game.js"); var player = require("./player.js"); new player("player"); new game("game"); modul

好吧,我算是明白了。但我想确定这是不可能的

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

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

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

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

    }
};
module.exports = class Game {
    constructor(arg){
        console.log(arg);
    }
};
index.js
player.js
我知道这会解决问题,但有没有其他方法不需要重复? (2个require,一个在
index.js
中,一个在
player.js
中)

index.js:

var player = require("./player.js");
var game = player.Game;
new player("player");
new game("game");
player.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;

你担心这件事有什么原因吗?它们对性能的影响几乎为零,这就像另一个变量名引用内存中已存在的对象将
Game
设计为
global.Game
,而不是
模块。导出
,那么你就不需要在任何地方使用它了。@ponury kostek在你已经有一个模块系统可以使用的情况下做这样的事情是一种反模式的行为,对吗?@CertainPerformance right,但这解决了他的“问题”:)答案是正确的,但实际上是一种伤害。OP显然在接受模块化环境的概念方面存在问题
Player
class充当名称空间没有很好的理由。@estus我100%同意