72. Class Methods and Properties
Inside a class, you define methods outside of the constructor function.
Adding Methods
Methods define the behavior of the class instances. They implicitly have access to the instance's properties via this.
javascript class Robot { constructor(name) { this.name = name; this.batteryLevel = 100; }
// Method definition
charge(amount) {
this.batteryLevel += amount;
console.log(`${this.name} charged. Level: ${this.batteryLevel}%`);
}
reportStatus() {
return `${this.name} is operational.`;
}
}
const unit1 = new Robot('C3P0'); unit1.charge(10); console.log(unit1.reportStatus());
Public Class Fields (New Syntax)
Modern JS allows you to define properties directly inside the class body, outside the constructor (often useful for setting defaults or configuration).
javascript class Config { // Public field definition version = 1.0; appName = 'Config Tool'; }
const cfg = new Config(); console.log(cfg.version); // 1.0