I'm building a simple quiz app and wanted to make it more scalable by putting my code into an object. The parameters list looks a bit messy to me. Is this a normal way to use an object or is there a better way?


// above here I have a JSON object with questions:
var quiz = new question($('#quiz-container'), $('.alert'), 0, [], questions[0].level[0]);

// for debugging

function question(quizContainer, alert, questionCounter, selection, level) {
    this.quizContainer = quizContainer;
    this.alert = alert;
    this.questionCounter = questionCounter;
    this.selection = selection;
    this.level = level;

    function createQuestion(index) {
  • \$\begingroup\$ I see issues with the current code. For instance, I think createQuestionshould be the single point to create an object (and should not be possible to call new Question()). The number of arguments passed to the constructor can be reduced too (#quiz-container is a global unique object, probably .alert is unique too), other default values such as 0 or [] can be set inside the constructor (no need to pass them as arguments). \$\endgroup\$ – Diego Pino Apr 17 '16 at 15:48

If you want to access the createQuestion function you could simply do the following

this.createQuestion = function(index){ 
    // your code

You can create public and private variables in a object. The easiest example I can give for this is using the following code.

function someObject(publicInput, privateInput) {

    this.public = publicInput;

    var private = privateInput;

    this.getPrivate = function(){
        return private;

var newObject = new someObject(true, false);

console.log(newObject.public); // returns true
console.log(newObject.private); // returns undefined
console.log(newObject.getPrivate()); // returns false

As you can see the private variable can only be accessed from inside the object, which is why I've added a getPrivate() function to return this variable.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.