如何处理Node.js中的循环依赖关系 [英] How to deal with cyclic dependencies in Node.js

查看:181
本文介绍了如何处理Node.js中的循环依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在使用nodejs,并且仍然对模块系统有所了解,因此如果这是一个明显的问题,我们深表歉意.我想要的代码大致如下:

I've been working with nodejs lately and still getting to grips with the module system so apologies if this is an obvious question. I want code roughly like the following below:

a.js (主要文件与节点一起运行)

a.js (the main file run with node)

var ClassB = require("./b");

var ClassA = function() {
    this.thing = new ClassB();
    this.property = 5;
}

var a = new ClassA();

module.exports = a;

b.js

var a = require("./a");

var ClassB = function() {
}

ClassB.prototype.doSomethingLater() {
    util.log(a.property);
}

module.exports = ClassB;

我的问题似乎是我无法从ClassB实例中访问ClassA实例.

My problem seems to be that I can't access the instance of ClassA from within an instance of ClassB.

是否有正确/更好的方法来构建模块以实现我想要的? 有没有更好的方法可以在模块之间共享变量?

Is there a correct / better way to structure modules to achieve what I want? Is there a better way to share variables between modules?

推荐答案

node.js确实允许循环require依赖关系,因为您发现它可以

While node.js does allow circular require dependencies, as you've found it can be pretty messy and you're probably better off restructuring your code to not need it. Maybe create a third class that uses the other two to accomplish what you need.

这篇关于如何处理Node.js中的循环依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆