加载上偏好不同模块
我想处理的图像文件的数组。当选择他们本人可以随机地或一个接一个地(队列)选择它们之间进行选择。这一决定是由config.json
举行。
第一I初始化处理器,并通过调用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;
}
当我运行的代码,random
是true
我得到这个错误
C:\ imageSelectors \ randomSelector.js:22
常量indexValue =的Math.random()* images.length;
类型错误:无法读取的未定义的属性“长度”
当调用imageSelector.init(images)
一些图像项可用,因此他们只是在模块内不确定的。
我想我误解了如何使用模块的正常工作。有人能告诉我如何正确设置代码?
回答如下:在你的模块,你声明一个局部变量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];
}