Vamos a ver como extraer un objeto en JavaScript en su versi贸n de ECMAScript 5. Partimos de un fichero donde tenemos todas las funcionalidades y vemos que una de ellas es claramente un objeto que podemos extraer.
// main.js
function application(){
// {...}
let actualQuestionIndex = 0;
function isThereMoreQuestions() {
return actualQuestionIndex < questions.length -1;
}
function getQuestion() {
return questions[actualQuestionIndex];
}
function goToNextQuestion() {
if (isThereMoreQuestions()) {
actualQuestionIndex++;
}
}
function resetQuestions() {
actualQuestionIndex = 0;
}
// {...}
}
Como podemos ver esta parte de nuestro c贸digo se encarga de la navegaci贸n en nuestras preguntas, por ello vamos a sacarlo a un nuevo fichero. Haciendo que nuestra aplicaci贸n sea m谩s modular y acepte cualquier tipo de navegaci贸n que cumpla estos requisitos m铆nimos.
//questionNavigator.js
var saberganar = saberganar || {};
saberganar.questionNavigator = function (questions){
let actualQuestionIndex = 0;
function isThereMoreQuestions() {
return actualQuestionIndex < questions.length -1;
}
function getQuestion() {
return questions[actualQuestionIndex];
}
function goToNextQuestion() {
if (isThereMoreQuestions()) {
actualQuestionIndex++;
}
}
function resetQuestions() {
actualQuestionIndex = 0;
}
return {
isThereMoreQuestions,
getNextQuestion
};
};
//main.js
var saberganar = saberganar || {};
saberganar.game = function(questionNavigator){
// {...}
let question = questionNavigator.getQuestion();
// {...}
}
De esta forma tambi茅n evitamos ensuciar el namespace de nuestra aplicaci贸n
dejando por separado cada m贸dulo namespace.game
y
namespace.questionNavigator