So… this actually has nothing to do with this
.
AJAX calls are asynchronous. This means that when you call quoteData.init()
, your get
request will be sent to the server, and then your code will skip past your callback function and continue, in your case, onto your console.log
. When your program receives a response from the server, then it will execute the stuff inside.
Because you haven’t received your data back from the server yet, your qData
variable hasn’t been defined yet. So, at the time you’re console.log
ging, qData
is undefined. If you make sure you console.log
(or otherwise try to access the qData
variable) after you’ve received a response from the server, then your qData
will actually have the information you want.
So, to illustrate this, if we move your console.log
into the get
request, and call quoteData.init()
on its own, we’d have:
$(document).ready(function() {
var quoteData = {
init: function () {
$.getJSON("https://got-quotes.herokuapp.com/quotes", function(qData) {
this.quoteString = qData.quote;
this.quoteCharacter = qData.character;
console.log(qData.quote);
console.log(qData.character);
});
},
quoteString: "",
quoteCharacter: ""
};
quoteData.init();
});
And in your console, you’ll now see your quote.
Until you learn about promises, the easiest way to ensure that whatever you need to do with your data is done in the callback function. (This can sometimes lead to what’s affectionately known as “callback hell,” but I’ll let you learn about that one on your own!)
Does all of that make sense? (Asynchronicity is an important concept to understand!)
Edit to add: this
is also a very important concept to understand, but isn’t necessarily your issue here.
(Although yes, it is true that the this.quoteString
inside of your get
is different from quoteString
later on. I’d personally recommend staying away from actually using this
until you feel like you have a decent grasp of what’s going on with it, because it can be a really, really confusing thing to grasp. Normal variables are cool too! 