ES6 引入的 JavaScript 类,是基于原型继承的语法糖衣,提供了一种更清晰、结构化的方法来定义和使用对象以及继承机制,从而提升代码的可读性和组织性。
使用 class 关键字定义类:
示例:
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`您好,我的名字是 ${this.name},我 ${this.age} 岁。`); } } const person1 = new Person("Alice", 25); person1.greet(); // 您好,我的名字是 Alice,我 25 岁。
构造函数 (constructor): 用于初始化对象实例的特殊方法,在创建新实例时自动调用。
立即学习“Java免费学习笔记(深入)”;
示例:
class Car { constructor(brand) { this.brand = brand; } } const myCar = new Car("Toyota"); console.log(myCar.brand); // Toyota
方法 (Methods): 类内部定义的函数。
示例:
class Animal { makeSound() { console.log("动物发出声音"); } } const dog = new Animal(); dog.makeSound(); // 动物发出声音
静态方法 (Static Methods): 使用 static 关键字定义,属于类本身,而非实例。
示例:
class MathUtils { static add(a, b) { return a + b; } } console.log(MathUtils.add(3, 5)); // 8
Getter 和 Setter: 用于访问和修改属性的特殊方法。
示例:
class Rectangle { constructor(width, height) { this.width = width; this.height = height; } get area() { return this.width * this.height; } } const rect = new Rectangle(10, 5); console.log(rect.area); // 50
使用 extends 关键字实现继承:
示例:
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} 发出声音。`); } } class Dog extends Animal { speak() { console.log(`${this.name} 汪汪叫。`); } } const dog = new Dog("Rex"); dog.speak(); // Rex 汪汪叫。
以 # 开头,只能在类内部访问。
示例:
class BankAccount { #balance; constructor(initialBalance) { this.#balance = initialBalance; } deposit(amount) { this.#balance += amount; console.log(`存款:${amount}`); } getBalance() { return this.#balance; } } const account = new BankAccount(100); account.deposit(50); // 存款:50 console.log(account.getBalance()); // 150 // console.log(account.#balance); // Error: 私有字段 '#balance' 无法访问
类可以定义为表达式并赋值给变量:
示例:
const Rectangle = class { constructor(width, height) { this.width = width; this.height = height; } getArea() { return this.width * this.height; } }; const rect = new Rectangle(10, 5); console.log(rect.getArea()); // 50
类可以与 JavaScript 的原型继承结合使用。
示例:
class Person {} Person.prototype.sayHello = function() { console.log("你好!"); }; const person = new Person(); person.sayHello(); // 你好!
JavaScript 类提供了一种更清晰、高效的面向对象编程方式,通过继承、静态方法、私有字段和封装等特性,方便构建可扩展、易维护的应用程序。
作者:Abhay Singh Kathayat
全栈开发人员,精通多种编程语言和框架。联系邮箱:kaashshorts28@gmail.com
以上就是掌握 JavaScript 类:现代 OOP 完整指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号