I feel my whole understanding of this has been thrown up in the air.
I have a Quiz object which holds the necessary variables and methods required to play the quiz.
I am trying to reference a method of Quiz from another method in Quiz (getQuestion in skipQuestion()) however, I am seeing a message in the console saying that this.getQuestion is not defined. I was under the impression that this in this case refers to the object it is in, hence the function in question should be referred to as this.getQuestion().
The error message I am getting is script.js:18 Uncaught TypeError: this.getQuestion is not a function
Can anyone explain what is going wrong here?
In my init function it seems that this refers to the Quiz object, but in skip question it seems to change. Is this down to query having a different definition of this? where do you draw the line, and when is the context of this changed?
(function(window){
$(document).ready(function(){
var Quiz = {
score : 0,
question: '',
answer: '',
init: function() {
this.getQuestion();
this.checkAnswer();
this.skipQuestion();
},
skipQuestion: function() {
$('#skip').click(function(){
this.getQuestion();
})
},
getQuestion: function() {
$.get('http://jservice.io/api/random', function(data){
$('#question').html(data[0].question);
this.answer = data[0].answer.toLowerCase();
});
},
checkAnswer: function() {
if($('#answer').val() === this.answer) {
this.score += 1;
}
}
}
Quiz.init();
});
})(window);
thiscontext changes. You either need to store thethisyou want to use as another variable before opening another function block, or you can use double arrow functions to not use a context like that altogether. The issues is:function(){ this.getQuestion(); }), which you can solve by doing this:var that = this; function(){ this.getQuestion(); })or by using an arrow function:() => { this.getQuestion() }(which has nothisobject associated with it).init()function it knows what the other functions are by usingthisbut not in theskipQuestionmethod? Is it because of query having different meaning ofthis?this. @ste2425 For simplicity you can say that they don't really have an associated context. Also, they don't allow calling or applyging with another context, so it doesn't really matter when writing code :)