最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何加载可变进模块出口,然后再使用

IT培训 admin 11浏览 0评论

如何加载可变进模块出口,然后再使用

所以,我有两个文件

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,因为它不会改变。

该如何才能随机函数访问helloArray?现在不顾API,我们可以一起工作[“嗨”,“你好”,“喜”]

回答如下:

您需要使用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
      }
}

如何加载可变进模块出口,然后再使用

所以,我有两个文件

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,因为它不会改变。

该如何才能随机函数访问helloArray?现在不顾API,我们可以一起工作[“嗨”,“你好”,“喜”]

回答如下:

您需要使用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
      }
}
发布评论

评论列表 (0)

  1. 暂无评论