I am completely new to Javascript but do have some experience in other languages (Java, Python, Swift) however it has been a while so I am not sure if I am misremembering some concepts or trying to apply concepts from other languages that don't work in JS.
Anyway, I want to create an instance of an object Booking from the data response from an API call.
This is what I have so far, so I have the booking object.
function Booking(id, retailer_id, app_date) {
this.id = id;
this.retailer_id = retailer_id;
this.app_date = app_date;
}
And I have my function that I can call getBooking(id)
function getBooking(booking_id) {
let request = new XMLHttpRequest();
let url = prefix.toString() + 'bookings/' + booking_id;
request.open('GET', url, true)
request.onload = function() {
let data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
return new Booking(data.id, data.retailer_id, data.app_date);
}
}
request.send();
console.log("Request sent.");
}
What I don't understand is why I can't just do :
let button = document.getElementById('button');
button.addEventListener('click', function() {
const booking = getBooking('1');
console.log(booking.id)
});
I've tried so many different things, I've tried declaring a variable as the object Booking() then overwriting with the output of the getBooking() function.
The only thing that worked is when i declared a public var
var booking = new Booking();
Then updated that variable inside the getBooking function.
But I don't want to have a static variable, I want to be able to create new instances of Booking object so that I can store the details retrieved from the API.