SoFunction
Updated on 2025-04-10

Introduction to classes in JavaScript and detailed explanation of application examples

1. The concept of class

What is a class?

In life, abstract concepts of things with similar attributes and behaviors, such as: humans, balls, and automobiles;

In JavaScript, a class is a template, a template used to create instance objects; it is equivalent to the prototype of the instance;

II. Use of classes

1. Grammar

class Class Name {  
  constructor(){
      ...
    }
  ...
}
  • class: ES6 provides the class keyword to create classes;
  • Class name: generally a noun, represented in capital letters, such as Person, Car...;
  • {......}: The class body is placed in a pair of braces. We can define the members of the class in braces, such as constructors, static methods, etc.;
  • constructor(){......}: Each class will contain a special method, the class constructor, used to instantiate an object created by class;

2. Example

// Define the classclass ClassName {
  // Construct method  constructor(name) {
     = name; // Instance properties  }
  static author = "zyl"; // Static properties
  #attr = 10; // Private attributes
  // Static method  static sFn(data) {
    return `I'm a static method,Can only be called by class name,The received parameters are${data};`;
  }

  // Ordinary method  fn(data) {
    (`The value of the private attribute is${this.#attr};`); // Access private attributes return `I am a normal method, and the received parameter is ${data};`;  }
}
// Instantiationconst class1 = new ClassName("First Class");
(class1); // ClassName {name: 'first class'}
// Access static properties(); // zyl

// Access instance properties(); // The first category
// Access static methods(("arg")); // I am a static method and can only be called through the class name, and the received parameter is arg;
// Access instance method(("123")); // The value of the private attribute is10; I'm the normal method,Calling via instance,The received parameters are123;

3. Class attributes

The properties in the JavaScript class include: static properties, instance properties, and private properties;

1. Static properties

The attributes of the class are defined using the static keyword, andClass name. Attribute name】access;

2. Instance properties

Define this in the constructor, byInstance.Attribute name】access;

3. Private attributes

use【#Attribute Name】 method is defined, and can only be accessed inside the class;

// Define the classclass ClassName {
  // Construct method  constructor(name) {
     = name; // Instance properties  }
  static author = "zyl"; // Static properties
  #attr = 10; // Private attributes  fn() {
    return this.#attr;
  }
}
// Instantiationconst class1 = new ClassName("First Class");
(class1); // ClassName {name: 'first class'}
// Access static properties();  // zyl

// Access instance properties();   // The first category
// Access private properties(()); // 10

IV. Class methods

The methods in the JavaScript class include: constructor methods, static methods, ordinary methods, and private methods;

1. Construction method

The construction method is a special method:

  • The name is constructor();
  • A constructor can be added to a class to instantiate the class;
  • In the construction method, object properties can be initialized;
  • When instantiating with the new keyword, constructor() will be automatically executed;
  • When defining a class, if the constructor() constructor method is not defined, JavaScript will automatically declare an empty constructor() method;
// Define Person classclass Person {
  constructor(name, age) {
     = name;
     = age;
  }
}

// Create a person1 instance objectconst person1 = new Person("zyl", 18);
(person1);         // Person {name: 'zyl', age: 18}

2. Static method

Use the static keyword definition, also known as a class method, which belongs to a class, not an instance object;

Static methods cannot be inherited, cannot be called through instances, can only be called through the current class name [Class name. Method name】 (The static methods of the parent class can be inherited by the child class);

// Define brand categoryclass Brand {
  constructor(name, type) {
     = name;
     = type;
  }

  // Static method to determine whether it is a VIP user  static isVip(count) {
    return count == "zylcount" ? "Vip User" : "New User";
  }

  // Static method to get brand discount price  static dPrice(price) {
    return price > 10 ? price * 0.9 : price * 0.95;
  }
}

const brand1 = new Brand("zylBrand", "clothing");
(brand1);                     // Brand {name: 'zylBrand', type: 'clothing'}

// Call static methods, called through the class name Brand, not instance brand1;(("1111111"));     // New users((12));           // 10.8

3. Ordinary method

Any number of ordinary methods can be defined in the class;

Ordinary methods are defined on the prototype of the class (prototype attribute) and will be inherited by the instance;

Calling through instanceExample. Method name】, cannot be called through class name;

// Define the car categoryclass Car {
  constructor(brand, price) {
     = brand;
     = price;
  }
  // Define ordinary methods  getInfo() {
    return `The brand of this car is${};The sale price is${}`;
  }
}
let car1 = new Car("volvo", "16.8w");
(car1);                 //  {brand: 'volvo', price: '16.8w'}

// Call normal methods through instance(());       // The brand of this car is volvo; the sale price is 16.8w
// Ordinary method is defined on the prototype of the Car class();   // {constructor: ƒ, getInfo: ƒ}
( === car1.__proto__.getInfo);   // true

5. Class inheritance

JavaScript allows us to rely on another class when creating one class; the created class is called [Subclasses/derived classes】, the dependency class is called [parent class/base class]; the subclass will inherit the properties and methods of the parent class, which is conducive to improving the reusability of the code;

1、extends

extends keyword, used for class inheritance; create a subclass to inherit a parent class, and the subclass will inherit all attributes and methods of the parent class;

(1) Syntax

class Subclass extends Parent class {
    // Define the properties and methods of subclasses    ...    
}

 (2) Example

class ParentClass {
  constructor(name, age) {
     = name;
     = age;
  }
  static attr = 'abc';
  static sFn(data){
    return `I am a static method defined in the parent class,The received parameters are:${data}`;
  }
  getInfo(data) {
    return `I'm a normal method defined in the parent class,The received parameters are:${data}`;
  }
}

class ChildClass extends ParentClass { }

const parent1 = new ParentClass('parent', '45');  
const child1 = new ChildClass('zyl', 20);  
(parent1);                 // ParentClass {name: 'parent', age: '45'}
(child1);                  // ChildClass {name: 'zyl', age: 20}
(ChildClass);              // class ChildClass extends ParentClass {}
();         // abc
(('1111'));  // I am defining the static method in the parent class, and the received parameter is: 1111((123));     // I'm a normal method defined in the parent class,The received parameters are:123

2、super

The super keyword is used to call the properties and methods of the parent class; when calling, you need to specify the parent class attribute or parent class method of the call;

super must be written before;

(1) Syntax

// Call the constructor of the parent classsuper();   
// Access parent class attributessuper.property;    
// Call parent class methodsuper.Method name(); 

(2) Example

// Define the parent classclass ParentClass {
  constructor(name, age, address) {
     = name;
     = age;
     = address;
  }
  static attr = "abc";
  static sFn(data) {
    return `I am a static method defined in the parent class,The received parameters are:${data}`;
  }
  getInfo(data) {
    return `I'm a normal method defined in the parent class,The received parameters are:${data}`;
  }
}

// Define subclasses and inherit parent classclass ChildClass extends ParentClass {
  constructor(name, age, address, phone) {
    // Call the constructor of the parent class    super(name, age,  address);
     = phone;
  }

  // Access the static properties of the parent class  static attr =  + "def";
  static sFn(data) {
    // Call the static method of the parent class    (`Subclass passsuperCall:${("Actual parameter of super call")}`);
    return `I'm defining a static method in a subclass,The received parameters are:${data}`;
  }
  getInfo(data) {
    // Call the normal method of the parent class    (`Subclass passsuperCall:${("Actual parameter of super call")}`);
    return `I'm a normal method defined in a subclass,The received parameters are:${data}`;
  }
}

const parent1 = new ParentClass("parent", 45 , "Shanghai");
const child1 = new ChildClass("child", 20, "Shanghai", '11111111');

(parent1);                 // ParentClass {name: 'parent', age: 45, address: 'Shanghai'}(child1);                  // ChildClass {name: 'child', age: 20, address: 'Shanghai'}
();        // abc
();         // abcdef

(("111"));  // I am defining the static method in the parent class, and the received parameter is: 111
(("222"));   // The subclass is called through super: I define the static method in the parent class, and the parameters received are: the actual parameter of the super call                                      // I am defining a static method in a subclass, and the parameters received are: 222
((123));    // I am a normal method defined in the parent class, and the parameters received are: 123((456));     // Subclass calls through super: I define the normal method in the parent class, and the parameters received are: the actual parameters of the super call                                      // I'm a normal method defined in a subclass,The received parameters are:456

Summarize

This is the article about the introduction and application of classes in JavaScript. For more detailed explanations of class classes in JS, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!