【问题标题】:Access variable in main node file from an imported file从导入的文件访问主节点文件中的变量
【发布时间】:2016-04-20 15:55:55
【问题描述】:
//in app.js
var x = require("x.js");
var instanceX = new x();
require("./Weather")();


//in Weather.js
instanceX.getName();

在这种情况下,从 Weather.js 引用时 instanceX 将不存在。如何在 Weather.js 中访问 instanceX?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    在模块设计中有许多不同的方法可以解决这个问题。一种简单的方法是将变量传递给 weather.js 构造函数:

    //in app.js
    var x = require("x.js");
    var instanceX = new x();
    require("./Weather")(instanceX);
    
    
    //in Weather.js
    var instanceX;
    module.exports = function(ix) {
        instanceX = ix;
    }
    
    // then elsewhere in the module
    instanceX.getName();
    

    我将其称为“推送”模型,因为您将内容推送到要与其共享的模块。

    【讨论】:

      猜你喜欢
      • 2016-09-18
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多