Home > Web Front-end > JS Tutorial > Classes in javascript

Classes in javascript

Mary-Kate Olsen
Release: 2025-01-22 14:38:10
Original
248 people have browsed it

Classes in javascript

JavaScript class

A class is a blueprint for an object, providing a more formal and organized way to define the object and its behavior. JavaScript classes are not objects themselves, but templates for creating JavaScript objects.

The

class is a special kind of function, but we use the keyword class to define it instead of function. Properties are assigned inside the constructor() method.

Class method

  1. The syntax of class methods is the same as that of object methods.
  2. Create a class using the class keyword.
  3. always contains a constructor() method.
  4. You can then add any number of methods.

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

<code class="language-javascript">class Car {
  constructor(brand) {
    this.carName = brand;
  }
}

let myCar = new Car("Toyota"); </code>
Copy after login

Constructor method

A constructor is a special method used to initialize objects created with a class. It is called automatically when a new instance of the class is created. It typically assigns values ​​to object properties using the parameters passed to it, ensuring that the object is properly initialized when created.

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() methods, which will cause a syntax error.

More class examples

<code class="language-javascript">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);</code>
Copy after login

The above is the detailed content of Classes in javascript. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template