1.JS中的类
class Person {
// 构造函数,用于初始化对象的属性
constructor(name, age) {
this.name = name;
this.age = age;
}
// 类的方法
introduce() {
return `我叫 ${this.name},今年 ${this.age} 岁。`;
}
// 静态属性
static PI = 3.14159;
// 静态方法
static calculateCircleArea(radius) {
return this.PI * radius * radius;
}
}
// 创建类的实例
const person1 = new Person('张三', 25);
console.log(person1.introduce()); // 输出: 我叫 张三,今年 25 岁。
原型链的抽象(即语法糖,之后会写原型链原理)(与学过的C#中类用法几乎相同)
重点:构造函数与类名相同(唯一),用constructor()初始化对象
静态属性和方法属于类本身,直接用类名.静态方法或属性访问,不能用实例调用
继承:extends关键字
class Student extends Person {
constructor(name, age, grade) {
// 调用父类的构造函数
super(name, age);
this.grade = grade;
}
// 重写父类的方法
introduce() {
return `我叫 ${this.name},今年 ${this.age} 岁,在读 ${this.grade} 年级。`;
}
}
const student1 = new Student('李四', 15, 9);
console.log(student1.introduce()); // 输出: 我叫 李四,今年 15 岁,在读 9 年级。
super()调用父类构造函数
访问器属性:get/set方法
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
// Getter 方法
get area() {
return this._width * this._height;
}
// Setter 方法
set width(value) {
if (value > 0) {
this._width = value;
} else {
console.error('宽度必须为正数。');
}
}
}
const rectangle = new Rectangle(5, 10);
console.log(rectangle.area); // 输出: 50
rectangle.width = -2; // 输出: 宽度必须为正数。
rectangle.width = 8;
console.log(rectangle.area); // 输出: 80
用于定义类的属性的获取和设置行为
类的私有属性和方法
用#标记,只能在类的内部访问
2.try...catch
捕获运行时错误,在 try
代码块中编写可能会抛出错误的代码,当错误发生时,JavaScript 会立即停止执行 try
块中的后续代码,并将控制权转移到 catch
代码块中。
3.fetch API
发送网络请求
fetch(url, options)
.then(response => {
// 处理响应
return response.json(); // 解析响应为 JSON 格式
})
.then(data => {
// 使用解析后的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error('请求出错:', error);
});
练习使用