当前位置:首页 > JavaScript

js实现class

2026-03-14 03:09:22JavaScript

实现类的基本语法

在JavaScript中,使用class关键字定义类。类可以包含构造函数、方法和属性。

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

  greet() {
    return `Hello, my name is ${this.name}`;
  }
}

const person = new Person('Alice', 25);
console.log(person.greet()); // 输出: Hello, my name is Alice

继承与扩展

通过extends关键字实现继承,子类可以覆盖或扩展父类的方法。

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age); // 调用父类构造函数
    this.grade = grade;
  }

  study() {
    return `${this.name} is studying in grade ${this.grade}`;
  }
}

const student = new Student('Bob', 18, 12);
console.log(student.study()); // 输出: Bob is studying in grade 12

静态方法与属性

静态方法属于类本身而非实例,通过static关键字定义。

class MathUtils {
  static add(a, b) {
    return a + b;
  }

  static PI = 3.14159;
}

console.log(MathUtils.add(2, 3)); // 输出: 5
console.log(MathUtils.PI); // 输出: 3.14159

Getter 与 Setter

通过getset定义属性的访问器,用于封装逻辑。

class Circle {
  constructor(radius) {
    this._radius = radius;
  }

  get radius() {
    return this._radius;
  }

  set radius(value) {
    if (value <= 0) throw new Error('Radius must be positive');
    this._radius = value;
  }

  get area() {
    return Math.PI * this._radius  2;
  }
}

const circle = new Circle(5);
console.log(circle.area); // 输出: 78.53981633974483
circle.radius = 10;
console.log(circle.area); // 输出: 314.1592653589793

私有字段

使用#前缀定义私有字段,仅在类内部可访问。

class Counter {
  #count = 0;

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

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

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 输出: 1
// console.log(counter.#count); // 报错: Private field must be declared in class

类表达式

类可以通过表达式形式定义,适合动态生成类。

js实现class

const Animal = class {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a noise`;
  }
};

const dog = new Animal('Dog');
console.log(dog.speak()); // 输出: Dog makes a noise

注意事项

  • 类声明不会提升,必须先定义后使用。
  • 类的方法默认不可枚举。
  • 类中的this指向实例,箭头函数可绑定上下文。

标签: jsclass
分享给朋友:

相关文章

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js实现点击显示和隐藏

js实现点击显示和隐藏

实现点击显示和隐藏的JavaScript方法 使用classList.toggle切换类名 通过添加/移除CSS类控制元素的显示与隐藏,需提前在CSS中定义隐藏样式(如display: none)。…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现祖玛

js实现祖玛

实现祖玛游戏的核心思路 祖玛游戏的核心玩法是发射彩色珠子,形成三个或以上相同颜色的珠子即可消除。以下是使用JavaScript实现的基本框架。 游戏初始化 创建画布并初始化游戏状态: const…