用js类的使用出练习题怎么控制难度
通过调整类中方法的访问权限、属性初始化复杂度以及是否引入继承链,可以精准控制练习题的难度。简单题使用单类与公开方法,中等难度加入私有字段和构造函数校验,高难度则结合原型链继承与多态调用。
基础:单类与公开方法
对于初学者,题目应聚焦于类的定义、实例化及基本属性的读写。此时不涉及复杂的逻辑分支或外部依赖,仅要求掌握 class 关键字的基本语法。
此类题目通常只包含一个类,所有方法均为公开状态。学生需要完成实例创建并调用方法获取结果。这种设置能确保学生理解对象与类的关系,而不会被内部实现细节干扰。
进阶:私有字段与构造函数校验
将程序保存为 exercise.js,在 Node.js 环境中运行 node exercise.js。若控制台输出正确的计算结果且无报错,即为成功。此阶段引入私有字段(以 # 开头)和参数校验,增加逻辑判断的必要性。
// 基础类:简单的计算器
class SimpleCalculator {
constructor(a, b) {
this.a = a;
this.b = b;
}
add() {
return this.a + this.b;
}
}
// 进阶类:带私有字段和校验的银行账户
class BankAccount {
#balance;
#owner;
constructor(owner, initialDeposit) {
if (typeof owner !== 'string' || !owner.trim()) {
throw new Error('Invalid owner name');
}
if (initialDeposit < 0) {
throw new Error('Initial deposit cannot be negative');
}
this.#owner = owner;
this.#balance = initialDeposit;
}
get balance() {
return this.#balance;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
}
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount;
return true;
}
return false;
}
}
// 高阶类:继承体系
class Shape {
constructor(color) {
this.color = color;
}
describe() {
return `A ${this.color} shape`;
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
describe() {
return `${super.describe()} with radius ${this.radius}`;
}
area() {
return Math.PI * this.radius ** 2;
}
}
// 测试用例
try {
const acc = new BankAccount('Alice', 100);
acc.deposit(50);
console.log(acc.balance); // 150
const circle = new Circle('red', 5);
console.log(circle.describe());
console.log(circle.area().toFixed(2));
} catch (e) {
console.error(e.message);
}
运行程序后,先输出 150,验证了进阶类中私有字段的封装与存取逻辑正确。接着输出 "A red shape with radius 5",展示了高阶类中 super.describe() 的正确调用与字符串拼接。接着输出 78.54,确认了面积计算公式无误。若修改初始存款为负数,程序将捕获异常并打印错误信息,体现了校验机制的有效性。
通过隐藏内部状态,迫使开发者必须通过特定的 getter/setter 或业务方法来交互。同时,在构造函数中加入类型检查或范围限制,使得非法输入无法生成有效实例,从而提升代码的健壮性要求。
高阶:继承链与多态行为
当子类重写父类方法时,需关注 super 调用的顺序及其对最终输出的影响。不同子类的同名方法返回结构差异是调试的关键点。
利用继承体系模拟真实场景中的分类处理。父类定义通用接口,子类实现特定逻辑。题目可要求识别因方法覆盖导致的行为变化,或分析组合模式下的属性访问路径。这考察了对原型链查找机制的深度理解。
js类的使用新手第一次用该从哪个功能开始
2026-11-24 09:21:38
不使用reverse方法,怎么用循环或递归实现JS字符串反转
2026-11-23 21:58:54
递归处理:怎么将嵌套JS对象扁平化为数组结构
2026-11-23 21:27:47
解决JS全局正则匹配失效:RegExp lastIndex陷阱与重置方法
2026-11-23 17:45:02
JavaScript请求超时后怎么实现自动重试机制
2026-11-23 17:44:33








![为什么JS对象直接转字符串显示[object Object]](https://img.javascript.cn/tit/articles/13236/20261106/84aa86eb15b66540a3d64b4a7a62b181d4058395daf4aec8f716e9fa4f562f53.webp)