JavaScript知识要点和ES6特性(来自卡片异步加载demo)

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);
  });

练习使用 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值