ECMAScript Class and Object Basics

In ECMAScript, an object is a data type that can contain properties and methods. Properties represent the characteristics or state of an object, while methods define its behavior or functionality. Objects can be created using literals, constructors, or the Object.create() method.

ECMAScript 6 introduced classes to simplify object creation and inheritance. A class acts as a template for creating objects by defining their properties and methods. It serves as a blueprint for generating multiple instances with identical attributes and behaviors.

In ECMAScript, classes are defined using the class keyword. Classes can include constructors, instance methods, and static methods. Constructors are used to instantiate objects, while methods define object behavior; static methods define class-level behavior.

Classes support inheritance via the extends keyword from other classes, enabling code reuse and extension. Inherited subclasses have access to parent properties and methods and can extend or override them as needed.

Objects and classes are fundamental language features in ECMAScript, supporting common programming patterns such as object-oriented programming (OOP), modularity, and inheritance. Understanding their usage and underlying principles is crucial for effective ECMAScript development.

// Class declaration
class Person1 {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}
let person1 = new Person1("name", 11);
console.log("Name of person1: " + person1.name);
console.log("Age of person1: " + person1.age);

// Class expression
const Person2 = class {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}
let person2 = new Person2("name", 11);
console.log("Name of person2: " + person2.name);
console.log("Age of person2: " + person2.age);

Objects

let person = {
    name: "personName",
    age: 11
};
console.log(person.name);
console.log(person.age);