根据偏好加载不同的模块

时间:2019-02-10 11:49:39

标签: javascript node.js

我想处理一组图像文件。选择它们时,我可以选择随机选择它们,也可以一一选择(队列)。该决定由config.json保留。

首先,我初始化处理器并通过调用processImages选择合适的图像选择模块,然后传入图像文件数组。

function processImages(images) {
    const imageSelector = getImageSelector();
    imageSelector.init(images); // initialize the module

    console.log(imageSelector.getImage()); // test
}

function getImageSelector() {
    const { random } = config;
    const selector = random ? 'randomSelector' : 'queueSelector';
    return require(`./imageSelectors/${selector}.js`);
}

模块本身具有返回下一个图像的逻辑。对于随机模块,我追求

let images;

module.exports = {
    init: images => {
        init(images);
    },
    getImage: () => {
        return getImage();
    }
};

function init(images) {
    this.images = images;
}

function getImage() {
    const index = getRandomIndex();
    return images[index];
}

function getRandomIndex() {
    const indexValue = Math.random() * images.length;
    const roundedIndex = Math.floor(indexValue);
    return images[roundedIndex];
}

我要去的队列模块

let images;
let currentImageCounter = 0;

module.exports = {
    init: images => {
        init(images);
    },
    getImage: () => {
        return getImage();
    }
};

function init(images) {
    this.images = images;
    currentImageCounter = 0;
}

function getImage() {
    const index = getNextIndex();
    return images[index];
}

function getNextIndex() {
    if (currentImageCounter > images.length)
        currentImageCounter = 0;
    else
        currentImageCounter++;

    return currentImageCounter;
}

当我运行代码并且randomtrue时出现此错误

  

C:... \ imageSelectors \ randomSelector.js:22

     

const indexValue = Math.random()* images.length;

     

TypeError:无法读取未定义的属性“ length”

调用imageSelector.init(images)时,有些图像项可用,因此它们在模块中是未定义的。

我想我误解了如何正确使用模块。有人可以告诉我如何正确设置代码吗?

1 个答案:

答案 0 :(得分:1)

在模块中,您声明一个局部变量images并将其用作对象字段this.images,这是不正确的。尝试这种方法,不要用名称相同的更深层变量遮盖上层变量(即不要使用images作为外部变量,而将类似imgs用作函数参数)。我还简化了您的模块代码,以避免不必要的重复。

let images;

module.exports = {
  init(imgs) {
    images = imgs;
  },
  getImage() {
    const index = getRandomIndex();
    return images[index];
  }
};

function getRandomIndex() {
  const indexValue = Math.random() * images.length;
  const roundedIndex = Math.floor(indexValue);
  return images[roundedIndex];
}