brienna
brienna

Reputation: 1604

Calling object method within the object—error: cannot read property of undefined

I'm trying to call getQuestions() inside the same object it is a method of. But when I try to read the quizz.config.allQuestions property, I get an error message reading "Uncaught TypeError: Cannot read property 'getQuestions' of undefined." Is there something I am missing here?

var quizz = {
    config: {
        urlJSON: 'questions.json',
        allQuestions: quizz.getQuestions()
    },

    getQuestions: function() {
        $.getJSON(quizz.config.urlJSON, function(questions) {
        return questions;
        });
    }
};

Upvotes: 1

Views: 1296

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

When you're trying to assign to allQuestions the quizz object isn't done being initialized yet. So you'd have to do it after creating the object.

var quizz = {
    config: {
      urlJSON: 'questions.json'
      // don't declare allQuestions
    },
    getQuestions: ...
};
quizz.allQuestions = quizz.getQuestions();

The problem with that though is that $.getJSON is an asynchronous function, meaning it won't return that value immediately. That's why it has a callback in it. Instead, you might try defining getQuestions like this:

getQuestions: function(callback) {
  $.getJSON(quizz.config.urlJSON, callback);
}

Then you can get the values like this:

quizz.getQuestions(function(questions) {
  quizz.config.allQuestions = questions;
});

Upvotes: 2

Related Questions