• JavaScript ES6类的主要功能


    标题JavaScript ES6类的主要功能

    JavaScript ES6(ECMAScript 6)引入了类(Class)的概念,这是对JavaScript面向对象编程模型的一种更清晰、更简洁的语法糖。虽然在ES6之前,我们可以通过构造函数和原型链实现类似类的行为,但ES6中的类语法更加接近传统面向对象语言如Java或C#。

    1.类声明:使用class关键字来定义一个类

    class Person {
      // ...
    }
    
    • 1
    • 2
    • 3

    2.构造函数:类中定义的特殊方法constructor用于创建并初始化新实例

    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3.实例属性和方法:在类内部可以定义实例属性和方法,这些将被所有类的实例共享

    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      sayHello() {
        console.log(`Hi, I am ${this.name} and I am ${this.age} years old.`);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    4.静态属性和方法:使用static关键字定义的属性和方法属于类本身,而不是其任何实例。

    class Person {
      static species = "Human";
      static getSpecies() {
        return this.species;
      }
    }
    console.log(Person.getSpecies()); // 输出 "Human"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    5.继承:通过extends关键字实现类之间的继承关系,并且子类可以使用super关键字调用父类的构造函数或其他方法

    class Employee extends Person {
      constructor(name, age, position) {
        super(name, age);
        this.position = position;
      }
    
      introduceYourself() {
        super.sayHello();
        console.log(`I work as a ${this.position}.`);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6.getter 和 setter:类中可以定义访问器属性(getter/setter),用来控制对对象属性的读取和赋值操作

    class Person {
      constructor(name, age) {
        this._age = age;
      }
    
      get age() {
        return this._age;
      }
    
      set age(value) {
        if (value >= 0) {
          this._age = value;
        } else {
          console.error("Age cannot be negative.");
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    2023年最新版Apollo保姆级使用手册(超级详尽版本)
    微服务网关 —— SpringCloud Gateway
    数据链路层(必备知识)
    XTU-OJ 1331-密码
    Nginx
    尚品汇电商项目总结
    M语言-模式匹配
    2.3 自定义msg C++
    typescript:命名空间
    springboot整合es
  • 原文地址:https://blog.csdn.net/webhhhhhh/article/details/136498578