您的位置:首页 > 新闻 > 资讯 > JS中【class】知识点详解

JS中【class】知识点详解

2025/2/26 7:55:32 来源:https://blog.csdn.net/2301_79858914/article/details/141089200  浏览:    关键词:JS中【class】知识点详解

JavaScript 中的 class 是一种语法糖,用于简化创建和管理对象的原型链和继承。虽然 JavaScript 的核心依然是基于原型继承的,但 class 语法让面向对象编程风格更加直观和易于使用。

1. 定义类

使用 class 关键字可以定义一个类。类通常包含构造函数和方法。

class Person {constructor(name, age) {this.name = name;this.age = age;}// 定义一个方法greet() {console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);}
}

2. 实例化类

使用 new 关键字来实例化类。

const person1 = new Person('Alice', 30);
person1.greet();  // 输出: Hello, my name is Alice and I am 30 years old.

3. 类的继承

使用 extends 关键字可以实现类的继承。

class Student extends Person {constructor(name, age, grade) {super(name, age);  // 调用父类的构造函数this.grade = grade;}study() {console.log(`${this.name} is studying in grade ${this.grade}.`);}
}const student1 = new Student('Bob', 20, 'A');
student1.greet();  // 输出: Hello, my name is Bob and I am 20 years old.
student1.study();  // 输出: Bob is studying in grade A.

4. 静态方法

使用 static 关键字定义静态方法,静态方法不需要实例化类即可调用。

class MathHelper {static add(x, y) {return x + y;}
}console.log(MathHelper.add(2, 3));  // 输出: 5

5. 私有字段与方法

在较新的 JavaScript 版本中,# 用于定义类的私有字段和方法。它们只能在类的内部访问,外部无法直接访问。

class Car {#speed = 0;accelerate(amount) {this.#speed += amount;console.log(`The car is now going ${this.#speed} mph.`);}#brake(amount) {this.#speed -= amount;if (this.#speed < 0) this.#speed = 0;console.log(`The car is now going ${this.#speed} mph.`);}
}const car1 = new Car();
car1.accelerate(50);
// car1.#brake(20); // 会报错,因为 #brake 是私有方法

6. 类的实例和原型

每个类都有一个关联的原型对象,它定义了该类实例的方法和属性。通过 Object.getPrototypeOf 可以获取实例的原型对象。

console.log(Object.getPrototypeOf(person1) === Person.prototype);  // 输出: true

7. 类表达式

类也可以通过表达式定义,并且可以是匿名的。

const Animal = class {constructor(type) {this.type = type;}makeSound() {console.log(`${this.type} makes a sound.`);}
};const dog = new Animal('Dog');
dog.makeSound();  // 输出: Dog makes a sound.

8. 类的语法与传统函数构造

虽然 class 语法看起来与传统的函数构造不同,但两者在底层实现上有很大的相似之处。class 本质上是语法糖,它简化了用构造函数和原型链来创建对象和处理继承的过程。

function Person(name, age) {this.name = name;this.age = age;
}Person.prototype.greet = function() {console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};const person2 = new Person('Charlie', 25);
person2.greet();  // 输出: Hello, my name is Charlie and I am 25 years old.

总结来说,JavaScript 的 class 提供了一个更简洁、更具表达力的方式来定义对象的行为和结构,同时也支持面向对象编程的常见特性如继承、封装和多态。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com