ES6中 class 类的使用(学习笔记)
2024-07-08 本文已影响0人
kevision
介绍
类是用于创建对象的模板。
我们使用 class 关键字来创建一个类,类体在一对大括号 {} 中,我们可以在大括号 {} 中定义类成员的位置,如方法或构造函数。
每个类中包含了一个特殊的方法 constructor(),它是类的构造函数,这种方法用于创建和初始化一个由 class 创建的对象。
创建类
class Runoob {
constructor(name, url) {
this.name = name;
this.url = url;
}
}
使用类
定义好类后,我们就可以使用 new 关键字来创建对象:
class Runoob {
constructor(name, url) {
this.name = name;
this.url = url;
}
}
let site = new Runoob("菜鸟教程", "https://www.runoob.com");
创建对象时会自动调用构造函数方法 constructor()。
类的方法
我们使用关键字 class 创建一个类,可以添加一个 constructor()方法,然后添加任意数量的方法。
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
类的继承
JavaScript 类继承使用 extends 关键字。
继承允许我们依据另一个类来定义一个类,这使得创建和维护一个应用程序变得更容易。
super()方法用于调用父类的构造函数。
当创建一个类时,您不需要重新编写新的数据成员和成员函数,只需指定新建的类继承了一个已有的类的成员即可。这个已有的类称为基类(父类),新建的类称为派生类(子类)。
class Site {
constructor(name) {
this.sitename = name;
}
present() {
return '我喜欢' + this.sitename;
}
}
class Runoob extends Site {
constructor(name, age) {
super(name); // 调用父类的构造函数,并把参数传过去
this.age = age;
}
show() {
// 继承了父类中的方法
return this.present() + ', 它创建了 ' + this.age + ' 年。';
}
}
let noob = new Runoob("菜鸟教程", 5);
document.getElementById("demo").innerHTML = noob.show(); // 我喜欢菜鸟教程, 它创建了 5 年
类的静态方法
静态方法是使用 static关键字修饰的方法,又叫类方法,属于类的,但不属于对象,在实例化对象之前可以通过 类名.方法名 调用静态方法。
静态方法不能在对象上调用,只能在类中调用。
class Runoob {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
let noob = new Runoob("菜鸟教程");
// 可以在类中调用 'hello()' 方法
document.getElementById("demo").innerHTML = Runoob.hello();
// 不能通过实例化后的对象调用静态方法
// document.getElementById("demo").innerHTML = noob.hello();
// 以上代码会报错
Class 和模块化的结合应用
- 使用 Class 和模块化实现一个简单的计算器:
// calculator.js
export class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
}
// main.js
import { Calculator } from './calculator.js';
const calculator = new Calculator();
console.log(calculator.add(1, 2)); // 输出:3
console.log(calculator.subtract(3, 2)); // 输出:1
- 使用 Class 和模块化实现一个简单的购物车:
// product.js
export class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
// cart.js
export class Cart {
constructor() {
this.products = [];
}
addProduct(product) {
this.products.push(product);
}
getTotalPrice() {
return this.products.reduce((total, product) => total + product.price, 0);
}
}
// main.js
import { Product } from './product.js';
import { Cart } from './cart.js';
const cart = new Cart();
const product1 = new Product("Apple", 1);
const product2 = new Product("Banana", 2);
cart.addProduct(product1);
cart.addProduct(product2);
console.log(cart.getTotalPrice()); // 输出:3
在上面的示例中,我们定义了一个 Product 的 Class 和一个 Cart 的 Class,并导出它们。在另一个文件中,我们通过导入 Product 和 Cart,并创建它们的实例,来实现一个简单的购物车功能。