Search code examples
javascriptnotationobject-literal

Two similar objects on the same page


I am working my way through a JavaScript book and am currently looking at creating objects with Literal Notation.

I am given this code:

var hotel = {
name: 'Quay',
rooms: 40,
booked:25,
checkAvailability: function() {
return this.rooms - this.booked;
 }
}

var hotelName = document.getElementById('hotel-name');
hotelName.textContent = hotel.name;

var freeRooms = document.getElementById('free-rooms');
freeRooms.textContent = hotel.checkAvailability();

I understand this perfectly fine.

It then tells me 'If you had two objects on the same page, you would create each one using the same notation but store them in variables with different names.'

I've tried to create this in JSFiddel but seem to be failing and I'm not sure why. Could anybody please post up a quick example and explaination. That'd be really helpful.

EDIT:: I am not sure whether it is telling me that I would write another object entirly or put some variables inside the existing object that link to name/rooms etc..

Thanks in advance.

Reference: John Duckett - JavaScript and JQuery


Solution

  • You can use this as a class, so you can reuse the Hotel object by typing new Hotel(name, rooms, booked)

    function Hotel(name, rooms, booked) {
      this.name = name;
      this.rooms = rooms;
      this.booked = booked;
    }
    
    Hotel.prototype = {
      checkAvailability: function() {
        return this.rooms - this.booked;
      }
    }
    
    var hotel = new Hotel('Quay', 40, 25);
    var hotel2 = new Hotel('Hotel2', 50, 45);
    
    var hotelName = document.getElementById('hotel-name-1');
    hotelName.textContent = hotel.name;
    
    var freeRooms = document.getElementById('free-rooms-1');
    freeRooms.textContent = hotel.checkAvailability();
    
    var hotelName = document.getElementById('hotel-name-2');
    hotelName.textContent = hotel2.name;
    
    var freeRooms = document.getElementById('free-rooms-2');
    freeRooms.textContent = hotel2.checkAvailability();
    <div id='hotel-name-1'></div>
    <div id='free-rooms-1'></div>
    <br>
    <div id='hotel-name-2'></div>
    <div id='free-rooms-2'></div>