"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Classes in javascript

Classes in javascript

Posted on 2025-02-22
Browse:242

Classes in javascript

JavaScript class

classes are blueprints for objects that provide a more formal and organized way to define objects and their behavior. The JavaScript class is not the object itself, but a template for creating JavaScript objects.

The

class is a special function, but we use the keyword class to define it, not the function. The attribute is assigned inside the constructor() method.

Class method

]
    The syntax of the
  1. class method is the same as that of the object method.
  2. Create classes using the class keyword.
  3. always contains the constructor() method.
  4. Any number of methods can then be added.

Example 1: Create a car class, and then create an object named "My Car" based on the car class.

class Car {
  constructor(brand) {
    this.carName = brand;
  }
}

let myCar = new Car("Toyota"); 

Constructor method

]

Constructor is a special method for initializing objects created with classes. It is called automatically when a new instance of the class is created. It usually uses the parameters passed to it to assign values ​​to the object properties, ensuring that the object is properly initialized at creation time.

When the constructor is automatically called and the class is initialized, it must have the exact name "constructor". In fact, if you don't have a constructor, JavaScript will add an invisible empty constructor method.

Note: A class cannot have multiple constructor(), which will throw a syntax error.

More Class Examples

class Person {} // 空类

class Student {
  constructor(rollNo, name, age) {
    this.name = name;
    this.rollNo = rollNo;
    this.age = age;
  }
}

let student1 = new Student(1, "Alex", 12);
console.log(student1); // Output: Student { name: 'Alex', rollNo: 1, age: 12 }

class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  displayProduct() {
    console.log(`Product: ${this.name}`);
    console.log(`Price: ${this.price}`);
  }
}

const product1 = new Product("Shirt", 19.32);
const product2 = new Product("Pant", 33.55);
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3