JavaScript Objects

Sept 15, 2022

Objects

Objects

An object groups together both variables and functions to create a model of an object, typically something that you would recognize as an object in the real world.

Within an object, variables are often referred to as properties and functions are often referred to as methods.

Creating an Object

Literal Notation

const marcumCenter = {
    name: 'Marcum Center',
    rooms: 40,
    booked: 25,
    getAvailabilityCount() {
        return this.rooms - this.booked;
    }
}

Creating an Object

Constructor

function Hotel(name, rooms, booked) {
    this.name = name;
    this.rooms = rooms;
    this.booked = booked;
    this.getAvailabilityCount = function() {
        return this.rooms - this.booked;
    };
}
const marcumCenter = new Hotel('Marcum Center', 40, 25);

Using and Object

console.log(marcumCenter.name);  // Marcum Center
console.log("Capacity: " + marcumCenter.booked + "/" + marcumCenter.rooms); // 25/40
console.log("Available: " + marcumCenter.getAvailabilityCount()); // 15