如何将变量加载到模块导出中,然后再使用

时间:2019-02-09 23:28:35

标签: node.js

所以我有两个文件

hi.js

var ext = require('./external.js')

ext.loadArray()
hello = ext.getRandom()
console.log(hello) // prints ['hey','hello','hi']

external.js

module.exports = {
      helloArray : [],
      loadArray: function(){
            //code that loads an array, ill manually enter for ? sake
            helloArray = ['hey','hello','hi'] 
      },
      getRandom: function(){
            return helloArray
      }
}

最后,我想返回helloArray的随机索引,但是没有填充它。当我在调用loadarray之后添加console.log(helloArray)时,该文件存在,但它并未进入getRandom函数。 loadArray从api加载信息,所以我不想调用该api,因为它不会更改。

get Random函数如何访问helloArray?现在暂时不用考虑API,我们可以使用['hey','hello','hi']

2 个答案:

答案 0 :(得分:0)

您需要使用this引用对象方法中的对象属性:

module.exports = {
      helloArray: [],
      loadArray: function(){
            //code that loads an array, ill manually enter for ? sake
            this.helloArray = ['hey','hello','hi']
      },
      getRandom: function(){
            return this.helloArray
      }
}

但是,如果不需要导出helloArray,则可以尝试以下操作:

var helloArray;

module.exports = {
      loadArray: function(){
            //code that loads an array, ill manually enter for ? sake
            helloArray = ['hey','hello','hi']
      },
      getRandom: function(){
            return helloArray
      }
}

答案 1 :(得分:0)

您也可以编写这样的代码

hi.js

var ext = new require('./external.js')

ext.loadArray()
console.log(ext.getRandom()) // prints ['hey','hello','hi']
console.log(ext.helloArray) // prints ['hey','hello','hi']

external.js

function external() {
    this.helloArray = [];
}
external.prototype.loadArray = function(){
    //code that loads an array, ill manually enter for ? sake
     this.helloArray = ['hey','hello','hi'] 
};

external.prototype.getRandom = function(){
    return  this.helloArray
};
module.exports = external;