es6引入class关键字,通过constructor定义实例属性和方法,使用extends实现继承并配合super调用父类,支持Static定义静态方法,get/set控制属性访问,使javaScript面向对象编程更清晰规范。

在ES6(ecmascript 2015)中,javascript引入了 class 关键字,让开发者可以用更清晰、更接近传统面向对象语言的方式来定义对象模板和实现继承。虽然JavaScript的类本质上仍然是基于原型(prototype)的语法糖,但 class 的写法更加直观和易于维护。
如何定义一个类
使用 class 关键字可以创建一个类。类中通常包含一个 constructor 构造方法,用于初始化实例属性,也可以定义其他方法。
示例:定义 Person 类
class Person { constructor(name, age) { this.name = name; this.age = age; } <p>// 实例方法 sayHello() { console.log(<code>你好,我是${this.name},今年${this.age}岁。</code>); }</p><p>// 获取年龄 getAge() { return this.age; } }</p><p>// 创建实例 const person1 = new Person("小明", 25); person1.sayHello(); // 输出:你好,我是小明,今年25岁。
类的继承(extends)
通过 extends 关键字可以实现类的继承,子类可以继承父类的属性和方法,并可通过 super 调用父类的构造函数或方法。
示例:Student 继承 Person
class Student extends Person { constructor(name, age, grade) { super(name, age); // 调用父类构造函数 this.grade = grade; } <p>// 重写方法 sayHello() { console.log(<code>我是学生 ${this.name},读 ${this.grade} 年级。</code>); }</p><p>// 新增方法 study() { console.log(<code>${this.name} 正在学习。</code>); } }</p><p>const student1 = new Student("小红", 20, "大三"); student1.sayHello(); // 输出:我是学生 小红,读 大三年级。 student1.study(); // 输出:小红 正在学习。 student1.getAge(); // 输出:20(继承自父类)
静态方法(static)
使用 static 关键字可以定义静态方法,静态方法属于类本身,不能通过实例调用,常用于工具函数或与类相关但不依赖实例的逻辑。
立即学习“Java免费学习笔记(深入)”;
示例:添加静态方法
class MathUtils { static add(a, b) { return a + b; } <p>static multiply(a, b) { return a * b; } }</p><p>console.log(MathUtils.add(3, 5)); // 输出:8 console.log(MathUtils.multiply(4, 6)); // 输出:24</p><p>// const utils = new MathUtils(); // utils.add(1, 2); // 错误:实例不能调用静态方法
getter 和 setter
可以在类中使用 get 和 set 定义访问器属性,用来控制属性的读取和赋值过程。
示例:使用 getter 和 setter
class BankAccount { constructor(initialBalance) { this._balance = initialBalance; } <p>get balance() { return <code>当前余额:${this._balance} 元</code>; }</p><p>set balance(amount) { if (amount < 0) { console.log("余额不能为负数!"); return; } this._balance = amount; } }</p><p>const account = new BankAccount(1000); console.log(account.balance); // 输出:当前余额:1000 元</p><p>account.balance = 500; console.log(account.balance); // 输出:当前余额:500 元</p><p>account.balance = -100; // 输出:余额不能为负数!
基本上就这些。class 让 JavaScript 的面向对象编程更规范,结合继承、静态方法和访问器,能写出结构清晰、易于扩展的代码。不复杂但容易忽略细节,比如 super 的使用时机和静态方法的调用方式。掌握这些,日常开发基本够用。