JavaScript and TypeScript course ยท Module 2: Functions, Arrays and Objects

Object Properties and Methods

13 min read ยท
In this lesson9

In the Jurassic Park management system, object properties and methods are key to modeling and controlling the behavior of the various parts of our complex. In this lesson we will take a closer look at the properties and methods of JavaScript objects and learn advanced techniques that help us keep our park and its residents in perfect condition.

Property Descriptors

In JavaScript every object property has not only a value, but also attributes that control how that property can be used. These attributes are known as property descriptors.

const dinosaur = {
  name: "Blue"
};

// Getting a property descriptor
const descriptor = Object.getOwnPropertyDescriptor(dinosaur, "name");
console.log(descriptor);
// Output: { value: "Blue", writable: true, enumerable: true, configurable: true }

A property descriptor contains the following fields:

  • value: the current value of the property
  • writable: whether the property can be changed
  • enumerable: whether the property shows up during iteration (e.g. in a for...in loop)
  • configurable: whether the descriptor can be changed and whether the property can be deleted

Defining Properties with Descriptors

We can define new properties with specific descriptors using Object.defineProperty():

const velociraptor = {};

// We define the "species" property with specific descriptors
Object.defineProperty(velociraptor, "species", {
  value: "Velociraptor",
  writable: false, // We cannot change the value
  enumerable: true, // It will appear during iteration
  configurable: false // We cannot change the descriptor or delete the property
});

console.log(velociraptor.species); // "Velociraptor"

// An attempt to change it will not work (in strict mode it throws an error)
velociraptor.species = "Tyrannosaurus";
console.log(velociraptor.species); // Still "Velociraptor"

// An attempt to delete it will not work
delete velociraptor.species; // Returns false
console.log(velociraptor.species); // Still "Velociraptor"

We can also define several properties at once:

const triceratops = {};

Object.defineProperties(triceratops, {
  species: {
    value: "Triceratops",
    writable: false
  },
  diet: {
    value: "herbivore",
    writable: false
  },
  age: {
    value: 5,
    writable: true // Age can change
  }
});

console.log(triceratops.species); // "Triceratops"
console.log(triceratops.diet); // "herbivore"
console.log(triceratops.age); // 5

triceratops.age = 6;
console.log(triceratops.age); // 6

Getters and Setters

Getters and setters are special methods that let you control access to an object's properties.

const dinosaur = {
  _health: 100, // The underscore convention signals that this is a private property

  // Getter - runs when we try to read the health property
  get health() {
    console.log("Reading the health level");
    return this._health;
  },

  // Setter - runs when we try to assign a value to the health property
  set health(value) {
    if (value < 0) {
      console.log("Warning: Attempt to set health below 0");
      this._health = 0;
    } else if (value > 100) {
      console.log("Warning: Attempt to set health above 100");
      this._health = 100;
    } else {
      console.log(`Setting the health level to ${value}`);
      this._health = value;
    }
  }
};

console.log(dinosaur.health); // Runs the getter, result: 100
dinosaur.health = 80; // Runs the setter
console.log(dinosaur.health); // 80
dinosaur.health = 150; // "Warning: Attempt to set health above 100"
console.log(dinosaur.health); // 100
dinosaur.health = -20; // "Warning: Attempt to set health below 0"
console.log(dinosaur.health); // 0

We can also define getters and setters using Object.defineProperty():

const dinosaur = {
  _name: "Rex",
  _species: "Tyrannosaurus"
};

Object.defineProperty(dinosaur, "fullName", {
  get: function() {
    return `${this._name} the ${this._species}`;
  },

  set: function(value) {
    // We assume that value has the format "Name the Species"
    const parts = value.split(" the ");
    if (parts.length === 2) {
      this._name = parts[0];
      this._species = parts[1];
    } else {
      console.log("Invalid format. Use: 'Name the Species'");
    }
  },

  enumerable: true,
  configurable: true
});

console.log(dinosaur.fullName); // "Rex the Tyrannosaurus"
dinosaur.fullName = "Blue the Velociraptor";
console.log(dinosaur._name); // "Blue"
console.log(dinosaur._species); // "Velociraptor"

Object Methods and Their Advanced Features

Binding this - the bind Method

The this keyword in methods refers to the object on which the method is called. However, in some cases (e.g. when we pass a method as a callback) we can lose the this context. The bind method lets you set the value of this explicitly.

const rex = {
  name: "Rex",
  makeSound: function() {
    console.log(`${this.name} roars loudly!`);
  }
};

// Normal behavior
rex.makeSound(); // "Rex roars loudly!"

// Problematic use - losing the this context
const rexSound = rex.makeSound;
// rexSound(); // Error: this.name is undefined

// Solution - using bind to set the value of this
const boundRexSound = rex.makeSound.bind(rex);
boundRexSound(); // "Rex roars loudly!"

// We can also set this to a different object
const blue = { name: "Blue" };
const blueSound = rex.makeSound.bind(blue);
blueSound(); // "Blue roars loudly!"

The call and apply Methods

The call and apply methods let you call a function with a specified this value and arguments:

function attack(target, damage) {
  console.log(`${this.name} attacks ${target} and deals ${damage} damage!`);
}

const trex = { name: "Tyrannosaurus Rex" };
const raptor = { name: "Velociraptor" };

// We use call with explicitly passed arguments
attack.call(trex, "Triceratops", 50);
// "Tyrannosaurus Rex attacks Triceratops and deals 50 damage!"

// We use apply with the arguments in an array
attack.apply(raptor, ["Gallimimus", 30]);
// "Velociraptor attacks Gallimimus and deals 30 damage!"

Object Properties as Symbols

Symbols provide unique identifiers that can be used as object property keys. They are especially useful for creating "private" properties or for extending objects without the risk of name collisions.

// Creating symbols
const healthSymbol = Symbol('health');
const nameSymbol = Symbol('name');

const dinosaur = {
  [nameSymbol]: "Blue",
  [healthSymbol]: 100,
  species: "Velociraptor"
};

console.log(dinosaur[nameSymbol]); // "Blue"
console.log(dinosaur[healthSymbol]); // 100

// Symbols are not visible in for...in loops
for (let key in dinosaur) {
  console.log(key); // Only "species", without nameSymbol and healthSymbol
}

// Nor in Object.keys()
console.log(Object.keys(dinosaur)); // ["species"]

// But you can get them with Object.getOwnPropertySymbols()
console.log(Object.getOwnPropertySymbols(dinosaur)); // [Symbol(name), Symbol(health)]

Well-Known Symbols

JavaScript defines several "well-known symbols" that let classes customize their behavior. The most commonly used one is Symbol.iterator, which makes objects iterable.

// We create a DinosaurPack object that will be iterable
class DinosaurPack {
  constructor() {
    this.dinosaurs = [];
  }

  addDinosaur(name, species) {
    this.dinosaurs.push({ name, species });
  }

  // Implementing iterability
  [Symbol.iterator]() {
    let index = 0;
    const dinosaurs = this.dinosaurs;

    return {
      next: function() {
        if (index < dinosaurs.length) {
          return { value: dinosaurs[index++], done: false };
        } else {
          return { done: true };
        }
      }
    };
  }
}

const pack = new DinosaurPack();
pack.addDinosaur("Blue", "Velociraptor");
pack.addDinosaur("Delta", "Velociraptor");
pack.addDinosaur("Echo", "Velociraptor");
pack.addDinosaur("Charlie", "Velociraptor");

// Now we can iterate over our object
for (const dino of pack) {
  console.log(`${dino.name} is a ${dino.species}`);
}
// Output:
// "Blue is a Velociraptor"
// "Delta is a Velociraptor"
// "Echo is a Velociraptor"
// "Charlie is a Velociraptor"

Freezing, Sealing and Preventing Extensions of Objects

JavaScript offers three methods for controlling how far objects can be modified:

Object.freeze()

Freezes an object (shallowly: nested objects can still be changed) - you cannot change existing properties or add new ones.

const securityProtocol = {
  level: "Maximum",
  status: "Active",
  lastUpdated: "2023-01-15"
};

// We freeze the object
Object.freeze(securityProtocol);

// Attempts to modify it will not work
securityProtocol.level = "Minimum"; // Will not change
securityProtocol.newProperty = "Value"; // Will not be added

console.log(securityProtocol.level); // Still "Maximum"
console.log(securityProtocol.newProperty); // undefined

console.log(Object.isFrozen(securityProtocol)); // true

Object.seal()

Seals an object - you can modify existing properties, but you cannot add new ones or delete existing ones.

const dinoStats = {
  health: 100,
  hunger: 50
};

// We seal the object
Object.seal(dinoStats);

// We can modify existing properties
dinoStats.health = 80;
console.log(dinoStats.health); // 80

// But we cannot add new ones
dinoStats.happiness = 90; // Will not work
console.log(dinoStats.happiness); // undefined

// Nor delete existing ones
delete dinoStats.hunger; // Will not work
console.log(dinoStats.hunger); // Still 50

console.log(Object.isSealed(dinoStats)); // true

Object.preventExtensions()

Prevents an object from being extended - you cannot add new properties, but you can modify and delete existing ones.

const dinosaur = {
  name: "Blue",
  species: "Velociraptor"
};

// We prevent extensions
Object.preventExtensions(dinosaur);

// We cannot add new properties
dinosaur.age = 4; // Will not work
console.log(dinosaur.age); // undefined

// But we can modify existing ones
dinosaur.name = "Delta";
console.log(dinosaur.name); // "Delta"

// And delete existing ones
delete dinosaur.species;
console.log(dinosaur.species); // undefined

console.log(Object.isExtensible(dinosaur)); // false

The Proxy Object

The Proxy object lets you intercept and customize basic operations on objects.

const dinosaur = {
  name: "Blue",
  species: "Velociraptor",
  health: 100,
  hunger: 50,
  aggressionLevel: 8
};

// We create a proxy for the dinosaur object
const monitoredDinosaur = new Proxy(dinosaur, {
  // We intercept the property read operation
  get: function(target, prop, receiver) {
    console.log(`Reading property: ${prop}`);
    return Reflect.get(target, prop, receiver);
  },

  // We intercept the property write operation
  set: function(target, prop, value, receiver) {
    console.log(`Setting ${prop} to ${value}`);

    // We add validation for some properties
    if (prop === 'health') {
      if (value < 0) value = 0;
      if (value > 100) value = 100;

      // Logging the health change
      const oldValue = target[prop];
      const change = value - oldValue;
      console.log(`Health change: ${change > 0 ? '+' : ''}${change}%`);

      // Checking whether the dinosaur is seriously injured
      if (value < 20 && oldValue >= 20) {
        console.log("ALARM: The dinosaur is seriously injured!");
      }
    }

    if (prop === 'aggressionLevel') {
      if (value > 7) {
        console.log("WARNING: High aggression level - security measures must be increased!");
      }
    }

    return Reflect.set(target, prop, value, receiver);
  },

  // We intercept the property delete operation
  deleteProperty: function(target, prop) {
    console.log(`Attempt to delete ${prop} - operation forbidden to keep the data safe`);
    return false; // We do not allow properties to be deleted
  }
});

// Testing our proxy
console.log(monitoredDinosaur.name); // "Reading property: name", "Blue"
monitoredDinosaur.health = 90; // "Setting health to 90", "Health change: -10%"
monitoredDinosaur.health = 15; // "Setting health to 15", "Health change: -75%", "ALARM: The dinosaur is seriously injured!"
monitoredDinosaur.aggressionLevel = 9; // "Setting aggressionLevel to 9", "WARNING: High aggression level..."
delete monitoredDinosaur.hunger; // "Attempt to delete hunger - operation forbidden to keep the data safe"

In Practice: A Dinosaur Health Monitoring System

Let's combine several of the techniques we have learned to build an advanced dinosaur health monitoring system for our park:

class DinosaurHealthMonitor {
  constructor() {
    this.dinosaurs = new Map();
    this.alarmThreshold = 30;
    this.criticalThreshold = 15;
    this.lastCheckTime = null;
  }

  // We add a dinosaur to the monitoring system
  addDinosaur(id, name, species) {
    if (this.dinosaurs.has(id)) {
      console.log(`A dinosaur with ID ${id} already exists in the system.`);
      return false;
    }

    const dinosaurData = {
      id,
      name,
      species,
      _health: 100,
      _lastFed: new Date(),
      _status: "Healthy",

      // We use a getter and a setter for health
      get health() {
        return this._health;
      },

      set health(value) {
        const oldHealth = this._health;
        this._health = Math.max(0, Math.min(100, value)); // Clamp to the 0-100 range

        // Update the status based on health
        if (this._health === 0) {
          this._status = "Critical - Emergency Response Required";
        } else if (this._health < 15) {
          this._status = "Critical";
        } else if (this._health < 30) {
          this._status = "Poor - Medical Attention Required";
        } else if (this._health < 60) {
          this._status = "Fair";
        } else if (this._health < 90) {
          this._status = "Good";
        } else {
          this._status = "Excellent";
        }

        return this._health;
      },

      // Method for feeding the dinosaur
      feed() {
        const now = new Date();
        const hoursSinceLastFed = (now - this._lastFed) / (1000 * 60 * 60);

        // The effect of feeding depends on how long ago the dinosaur was last fed
        if (hoursSinceLastFed < 1) {
          console.log(`${this.name} is not hungry (fed less than an hour ago).`);
          return false;
        } else {
          const healthGain = Math.min(10, hoursSinceLastFed * 2); // At most 10 health points
          this.health += healthGain;
          this._lastFed = now;

          console.log(`${this.name} has been fed. +${healthGain.toFixed(1)} health. Current level: ${this.health}%`);
          return true;
        }
      }
    };

    // We use Object.seal to prevent new properties from being added
    Object.seal(dinosaurData);

    // We add the dinosaur to the map
    this.dinosaurs.set(id, dinosaurData);
    console.log(`Added dinosaur ${name} (${species}) to the health monitoring system.`);
    return true;
  }

  // Getting information about a dinosaur
  getDinosaurInfo(id) {
    if (!this.dinosaurs.has(id)) {
      return `A dinosaur with ID ${id} does not exist in the system.`;
    }

    const dino = this.dinosaurs.get(id);
    return {
      id: dino.id,
      name: dino.name,
      species: dino.species,
      health: dino.health,
      status: dino._status,
      lastFed: dino._lastFed
    };
  }

  // Method that simulates the passage of time, which lowers the dinosaurs' health
  simulateTimePass(hours) {
    console.log(`Simulating the passage of ${hours} hours...`);

    this.dinosaurs.forEach(dino => {
      // Health reduction - the rate depends on the species
      let healthReduction = hours;

      if (dino.species.toLowerCase().includes('tyrannosaurus')) {
        healthReduction *= 1.5; // Tyrannosaurus loses health faster
      } else if (dino.species.toLowerCase().includes('velociraptor')) {
        healthReduction *= 1.2; // Velociraptors fairly fast too
      }

      const newHealth = dino.health - healthReduction;
      dino.health = newHealth;

      console.log(`${dino.name}: Health reduced by ${healthReduction.toFixed(1)} to ${dino.health}% (${dino._status})`);
    });

    this.lastCheckTime = new Date();
    this.checkAlarms();
  }

  // Checking health alarms
  checkAlarms() {
    console.log("Checking health alarms...");

    const criticalDinos = [];
    const alarmDinos = [];

    this.dinosaurs.forEach(dino => {
      if (dino.health <= this.criticalThreshold) {
        criticalDinos.push(dino);
      } else if (dino.health <= this.alarmThreshold) {
        alarmDinos.push(dino);
      }
    });

    if (criticalDinos.length > 0) {
      console.log("=== CRITICAL HEALTH CONDITION ===");
      criticalDinos.forEach(dino => {
        console.log(`- ${dino.name} (${dino.species}): ${dino.health}% - REQUIRES IMMEDIATE INTERVENTION!`);
      });
    }

    if (alarmDinos.length > 0) {
      console.log("=== HEALTH ALARM ===");
      alarmDinos.forEach(dino => {
        console.log(`- ${dino.name} (${dino.species}): ${dino.health}% - Needs veterinary care`);
      });
    }

    if (criticalDinos.length === 0 && alarmDinos.length === 0) {
      console.log("All dinosaurs are in good health.");
    }
  }

  // Generating a report for all dinosaurs
  generateHealthReport() {
    const now = new Date();
    let report = `=== DINOSAUR HEALTH REPORT (generated: ${now.toLocaleString()}) ===\n`;

    if (this.dinosaurs.size === 0) {
      report += "No dinosaurs in the monitoring system.\n";
    } else {
      // Sorting the dinosaurs by health level (lowest first)
      const sortedDinos = [...this.dinosaurs.values()].sort((a, b) => a.health - b.health);

      sortedDinos.forEach(dino => {
        report += `${dino.name} (${dino.species})\n`;
        report += `  Health: ${dino.health}% (${dino._status})\n`;
        report += `  Last fed: ${dino._lastFed.toLocaleString()}\n`;

        // We add recommendations
        if (dino.health < this.criticalThreshold) {
          report += "  RECOMMENDATION: Immediate veterinary intervention! Transfer to the intensive care unit.\n";
        } else if (dino.health < this.alarmThreshold) {
          report += "  RECOMMENDATION: More frequent feeding and veterinary checks.\n";
        }

        report += "\n";
      });
    }

    return report;
  }
}

// Usage example
const healthMonitor = new DinosaurHealthMonitor();

// We add a few dinosaurs
healthMonitor.addDinosaur("TRX-01", "Rex", "Tyrannosaurus Rex");
healthMonitor.addDinosaur("VEL-01", "Blue", "Velociraptor");
healthMonitor.addDinosaur("TRI-01", "Trixie", "Triceratops");
healthMonitor.addDinosaur("BRACH-01", "Bronty", "Brachiosaurus");

// We generate the initial report
console.log(healthMonitor.generateHealthReport());

// We simulate the passage of time
healthMonitor.simulateTimePass(24); // 24 hours

// We feed some of the dinosaurs
const rex = healthMonitor.dinosaurs.get("TRX-01");
const blue = healthMonitor.dinosaurs.get("VEL-01");
rex.feed();
blue.feed();

// We simulate more time passing
healthMonitor.simulateTimePass(48); // 48 hours

// We generate the final report
console.log(healthMonitor.generateHealthReport());

Summary

In this lesson we explored advanced properties and methods of JavaScript objects:

  1. Property descriptors - give you precise control over the attributes of properties
  2. Getters and setters - let you run code when a property is read or written
  3. Binding this - the bind, call and apply methods help you control the context of a function
  4. Symbols - provide unique identifiers for object properties
  5. Freezing objects - the freeze, seal and preventExtensions methods let you limit how far objects can be modified
  6. Proxy - lets you intercept and customize basic operations on objects

These techniques are essential when building complex systems such as our dinosaur health monitoring system in Jurassic Park. They let you create more reliable, secure and elegant software solutions.

Code for this lesson: index.js
// Object properties and methods - Jurassic Park
console.log("Object Properties and Methods");
console.log("Advanced operations on objects\n");

// ===========================================
// 1. ACCESSING PROPERTIES
// ===========================================
console.log("=== 1. Access to properties ===");

const dinosaur = {
  name: "T-Rex",
  species: "Tyrannosaurus Rex",
  age: 8,
  "sector-id": "A-7", // Property with a hyphen
  weight: 8000
};

// Dot notation
console.log("\nDot notation:");
console.log(`   name: ${dinosaur.name}`);
console.log(`   age: ${dinosaur.age}`);

// Bracket notation
console.log("\nBracket notation:");
console.log(`   ['species']: ${dinosaur['species']}`);
console.log(`   ['sector-id']: ${dinosaur['sector-id']}`); // Required for hyphens

// Dynamic access
const prop = "weight";
console.log(`\nDynamic access [${prop}]: ${dinosaur[prop]}`);

// ===========================================
// 2. ADDING AND MODIFYING PROPERTIES
// ===========================================
console.log("\n=== 2. Adding and modifying ===");

const dino = {
  name: "Blue",
  species: "Velociraptor"
};

console.log("\nInitially:", dino);

// Adding new properties
dino.age = 5;
dino.weight = 80;
dino["sector"] = "B";

console.log("After adding:", dino);

// Modifying existing
dino.age = 6;
dino.weight = 85;

console.log("After modification:", dino);

// ===========================================
// 3. REMOVING PROPERTIES
// ===========================================
console.log("\n=== 3. Removing properties ===");

const tempDino = {
  name: "Charlie",
  species: "Velociraptor",
  tempId: 12345,
  debugMode: true
};

console.log("\nBefore removal:", tempDino);

delete tempDino.tempId;
delete tempDino.debugMode;

console.log("After removal:", tempDino);

// ===========================================
// 4. CHECKING PROPERTY EXISTENCE
// ===========================================
console.log("\n=== 4. Checking existence ===");

const checkDino = {
  name: "Rexy",
  age: 8,
  sector: null
};

// The 'in' operator
console.log("\nThe 'in' operator:");
console.log(`   'name' in checkDino: ${'name' in checkDino}`);
console.log(`   'weight' in checkDino: ${'weight' in checkDino}`);
console.log(`   'sector' in checkDino: ${'sector' in checkDino}`); // true despite null!

// hasOwnProperty()
console.log("\nhasOwnProperty():");
console.log(`   hasOwnProperty('name'): ${checkDino.hasOwnProperty('name')}`);
console.log(`   hasOwnProperty('toString'): ${checkDino.hasOwnProperty('toString')}`); // false (inherited)

// undefined check
console.log("\nChecking undefined:");
console.log(`   name !== undefined: ${checkDino.name !== undefined}`);
console.log(`   weight !== undefined: ${checkDino.weight !== undefined}`);

// ===========================================
// 5. ITERATING OVER PROPERTIES
// ===========================================
console.log("\n=== 5. Iteration over properties ===");

const iterDino = {
  name: "Trike",
  species: "Triceratops",
  age: 7,
  weight: 9000,
  sector: "C"
};

// for...in
console.log("\nfor...in:");
for (const key in iterDino) {
  console.log(`   ${key}: ${iterDino[key]}`);
}

// Object.keys()
console.log("\nObject.keys():");
const keys = Object.keys(iterDino);
console.log(`   Keys: ${keys.join(", ")}`);

// Object.values()
console.log("\nObject.values():");
const values = Object.values(iterDino);
console.log(`   Values: ${values.join(", ")}`);

// Object.entries()
console.log("\nObject.entries():");
Object.entries(iterDino).forEach(([key, value]) => {
  console.log(`   ${key} => ${value}`);
});

// ===========================================
// 6. OBJECT METHODS
// ===========================================
console.log("\n=== 6. Object methods ===");

const methodDino = {
  name: "Stego",
  species: "Stegosaurus",
  health: 85,

  // Traditional method
  getInfo: function() {
    return `${this.name} (${this.species})`;
  },

  // Shorthand method (ES6)
  roar() {
    return `${this.name} says: ROAARRR!`;
  },

  // Method with parameters
  updateHealth(change) {
    this.health += change;
    if (this.health > 100) this.health = 100;
    if (this.health < 0) this.health = 0;
    return `Health: ${this.health}%`;
  },

  // Method returning an object
  getStats() {
    return {
      name: this.name,
      health: this.health,
      status: this.health >= 80 ? "Healthy" : "Needs attention"
    };
  }
};

console.log("\n", methodDino.getInfo());
console.log("   ", methodDino.roar());
console.log("   ", methodDino.updateHealth(10));
console.log("   Stats:", methodDino.getStats());

// ===========================================
// 7. THIS IN METHODS
// ===========================================
console.log("\n=== 7. The 'this' context in methods ===");

const thisDino = {
  name: "Brachio",
  sector: "D",

  showInfo() {
    console.log(`\n${this.name} in sector ${this.sector}`);
  },

  // Problem with a nested function
  showWithTraditional() {
    console.log(`\n${this.name}:`);

    ["Feeding", "Examination", "Cleaning"].forEach(function(task) {
      // this here does NOT refer to thisDino!
      console.log(`   - ${task}`); // We cannot use this.name
    });
  },

  // Solution with an arrow function
  showWithArrow() {
    console.log(`\n${this.name}:`);

    ["Feeding", "Examination", "Cleaning"].forEach(task => {
      console.log(`   - ${task} for ${this.name}`); // this works!
    });
  }
};

thisDino.showInfo();
thisDino.showWithTraditional();
thisDino.showWithArrow();

// ===========================================
// 8. COMPUTED PROPERTY NAMES
// ===========================================
console.log("\n=== 8. Computed property names ===");

const propName = "species";
const propValue = "Velociraptor";
const sectorNumber = 7;

const computedDino = {
  name: "Echo",
  [propName]: propValue, // Computed property name
  [`sector-${sectorNumber}`]: true,
  [`health_${Date.now()}`]: 95
};

console.log("\nObject with computed names:");
console.log(computedDino);

// ===========================================
// 9. PROPERTY DESCRIPTORS
// ===========================================
console.log("\n=== 9. Property descriptors ===");

const descriptorDino = {};

// Defining properties with descriptors
Object.defineProperty(descriptorDino, 'name', {
  value: "Rex",
  writable: true,
  enumerable: true,
  configurable: true
});

Object.defineProperty(descriptorDino, 'id', {
  value: 12345,
  writable: false, // Read-only
  enumerable: false, // Does not appear in for...in
  configurable: false // Cannot remove or change the descriptor
});

console.log("\nProperties:");
console.log(`   name: ${descriptorDino.name}`);
console.log(`   id: ${descriptorDino.id}`);

console.log("\nModification attempt:");
descriptorDino.name = "Rexy"; // Will work
console.log(`   name after the change: ${descriptorDino.name}`);

descriptorDino.id = 99999; // Won't work (writable: false)
console.log(`   id after the change attempt: ${descriptorDino.id}`);

console.log("\nfor...in (id does not appear):");
for (const key in descriptorDino) {
  console.log(`   ${key}: ${descriptorDino[key]}`);
}

// ===========================================
// 10. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 10. Dinosaur management system - complex example ===");

class DinosaurManager {
  constructor(name, species) {
    // Basic properties
    this._name = name;
    this._species = species;
    this._health = 100;
    this._fed = false;
    this._lastFed = null;
    this._activities = [];

    // Computed properties
    Object.defineProperty(this, 'id', {
      value: `DINO-${Date.now()}`,
      writable: false,
      enumerable: true
    });
  }

  // Getters and setters
  get name() {
    return this._name;
  }

  get species() {
    return this._species;
  }

  get health() {
    return this._health;
  }

  set health(value) {
    if (value < 0) value = 0;
    if (value > 100) value = 100;

    const oldHealth = this._health;
    this._health = value;

    this.logActivity(`Health changed from ${oldHealth}% to ${value}%`);
  }

  get status() {
    if (this._health >= 80) return "Excellent";
    if (this._health >= 50) return "Good";
    if (this._health >= 20) return "Weak";
    return "Critical";
  }

  get needsFeeding() {
    if (!this._lastFed) return true;
    const hoursSinceLastFed = (Date.now() - this._lastFed) / (1000 * 60 * 60);
    return hoursSinceLastFed > 8;
  }

  // Action methods
  feed() {
    this._fed = true;
    this._lastFed = Date.now();
    this.health += 5;
    this.logActivity("Fed");
    return `${this._name} has been fed`;
  }

  heal(amount) {
    this.health += amount;
    this.logActivity(`Healed (+${amount}% health)`);
    return `${this._name} healed by ${amount}%`;
  }

  exercise() {
    this.health -= 5;
    this.logActivity("Exercised");
    return `${this._name} performed exercises`;
  }

  // Helper methods
  logActivity(activity) {
    this._activities.push({
      activity,
      timestamp: new Date().toISOString(),
      health: this._health
    });
  }

  getActivityLog(limit = 5) {
    return this._activities.slice(-limit);
  }

  getInfo() {
    return {
      id: this.id,
      name: this._name,
      species: this._species,
      health: this._health,
      status: this.status,
      fed: this._fed,
      needsFeeding: this.needsFeeding,
      activitiesCount: this._activities.length
    };
  }

  displayReport() {
    console.log(`\n==================================================`);
    console.log(`DINOSAUR REPORT: ${this._name}`);
    console.log("=".repeat(50));

    const info = this.getInfo();
    console.log(`ID: ${info.id}`);
    console.log(`Species: ${info.species}`);
    console.log(`Health: ${info.health}% (${info.status})`);
    console.log(`Fed: ${info.fed ? "Yes" : "No"}`);
    console.log(`Needs feeding: ${info.needsFeeding ? "Yes" : "No"}`);
    console.log(`Number of activities: ${info.activitiesCount}`);

    const recentActivities = this.getActivityLog(5);
    if (recentActivities.length > 0) {
      console.log(`\nRecent activities:`);
      recentActivities.forEach((act, i) => {
        const time = new Date(act.timestamp).toLocaleTimeString();
        console.log(`  ${i + 1}. [${time}] ${act.activity} (health: ${act.health}%)`);
      });
    }
  }

  // Static method
  static compare(dino1, dino2) {
    console.log(`\nComparison: ${dino1.name} vs ${dino2.name}`);
    console.log(`   Health: ${dino1.health}% vs ${dino2.health}%`);
    console.log(`   Status: ${dino1.status} vs ${dino2.status}`);

    if (dino1.health > dino2.health) {
      console.log(`   ${dino1.name} is healthier`);
    } else if (dino2.health > dino1.health) {
      console.log(`   ${dino2.name} is healthier`);
    } else {
      console.log(`   Both have the same health`);
    }
  }
}

// System demonstration
const rexy = new DinosaurManager("Rexy", "T-Rex");
const blue = new DinosaurManager("Blue", "Velociraptor");

console.log();
console.log(rexy.feed());
console.log(rexy.exercise());
console.log(rexy.heal(10));

console.log();
console.log(blue.feed());
console.log(blue.exercise());
console.log(blue.exercise());

rexy.displayReport();
blue.displayReport();

DinosaurManager.compare(rexy, blue);

console.log("\nCongratulations! You've mastered object properties and methods!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is Object.defineProperty() used for in JavaScript?

  2. 2. What are getters (get) and setters (set) used for in JavaScript objects?

Hands-on tasks in the game

  • Click in order

    Arrange the elements of a getter definition in an object:

  1. QuestionObject Basics - Object.defineProperty
  2. QuestionObject Basics - Getters and Setters
  3. Click in orderObject Basics - Getter Syntax

Useful articles