es6 基础学习之class的相关

ES6 中的 class

在 ES6(ECMAScript 2015)中,class 关键字引入了一种新的方式来创建和继承对象。这种语法更接近传统的面向对象编程语言,如 Java 和 C++,从而使得对象模型更易理解和使用。

基础语法

下面是一个简单的 class 定义:

javascript 复制代码
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const john = new Person('John', 30);
john.sayHello();  // 输出 "Hello, my name is John"

构造函数 constructor

constructor 是一个特殊的方法,用于创建和初始化由 class 创建的对象。一个类只能拥有一个名为 "constructor" 的特殊方法。

实例方法和属性

在 constructor 方法中定义的属性和方法是实例属性和方法,每个实例对象都有自己的一份。

静态方法和属性

使用 static 关键字,你可以定义一个类的静态方法。静态方法不会出现在类的实例上,而是直接出现在类本身上。

javascript 复制代码
class MathHelper {
  static square(x) {
    return x * x;
  }
}

console.log(MathHelper.square(5));  // 输出 25

继承(Inheritance)

使用 extends 关键字创建一个类作为另一个类的子类。

javascript 复制代码
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);  // 调用父类的 constructor
    this.grade = grade;
  }

  sayGrade() {
    console.log(`I am in grade ${this.grade}`);
  }
}

const jane = new Student('Jane', 20, 'Grade 1');
jane.sayHello();  // 输出 "Hello, my name is Jane"
jane.sayGrade();  // 输出 "I am in grade Grade 1"

访问器(Getters 和 Setters)

你可以使用 get 和 set 关键字来创建对象属性的访问器。

javascript 复制代码
class Circle {
  constructor(radius) {
    this._radius = radius;
  }

  get radius() {
    return this._radius;
  }

  set radius(value) {
    if (value <= 0) {
      console.log('Invalid radius');
    } else {
      this._radius = value;
    }
  }
}

const circle = new Circle(5);
console.log(circle.radius);  // 输出 5

circle.radius = -1;  // 输出 "Invalid radius"

私有属性和方法(提案)

目前,JavaScript 还没有提供原生的方式来定义私有属性和方法,但有一个字段声明的提案,使用 # 符号来声明私有属性。

javascript 复制代码
class Counter {
  #count = 0;

  increment() {
    this.#count++;
  }

  getCount() {
    return this.#count;
  }
}

这些是 ES6 中 class 的主要特性和用法。这些新特性提供了一种更结构化、更面向对象的方式来组织代码,使得 JavaScript 变得更加灵活和强大。希望这些信息能帮助你更好地理解和使用 ES6 中的 class 特性。

相关推荐
专业程序开发源10 小时前
springboot简历管理系统81389-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·php·课程设计
专业程序开发源10 小时前
springboot社区养老系统44071-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·php·课程设计
码艺-Alimjan11 小时前
Vben Admin 新增维吾尔语 Vben-Modal的关键坑之一
前端·javascript·vue.js
星光开发者12 小时前
基于决策树随机森林算法的小说推荐系统的设计与实现-计算机毕设【课程设计】78485
vue.js·算法·微信小程序·django·php·课程设计·express
vx_Biye_Design13 小时前
springboot高校选课系统82776-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·课程设计·express
niyongsheng13 小时前
后端零改动,给若依换一套现代化前端
vue.js·开源·node.js
用户91775337187516 小时前
从零封装一个地图组件库:OpenLayers + Vue 的工程化实践
vue.js
雪芽蓝域zzs17 小时前
第7节:多选模式、自定义选项渲染、受控弹窗显隐
vue.js·elementui
acd1200918 小时前
前端随笔:数据明明变了,Vue 页面就是不更新
前端·javascript·vue.js
vx_Biye_Design18 小时前
springboot一站式旅游管理平台81037-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·课程设计·express·旅游