class Person {
// 构造函数
constructor(name, age) {
this.name = name;
this.age = age;
}
// 实例方法
introduce() {
console.log(`我叫${this.name},今年${this.age}岁`);
}
// 静态方法
static sayHello() {
console.log("你好!");
}
}
// 创建实例
const person1 = new Person("张三", 25);
person1.introduce(); // 我叫张三,今年25岁
Person.sayHello(); // 你好!
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name}在吃东西`);
}
speak() {
console.log(`${this.name}发出声音`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 必须调用父类的构造函数
this.breed = breed;
}
// 重写父类方法
speak() {
console.log(`${this.name}汪汪叫`);
}
// 扩展新方法
fetch() {
console.log(`${this.name}接住了球`);
}
// 调用父类方法
eat() {
super.eat(); // 先执行父类的eat方法
console.log(`${this.name}吃得很开心`);
}
}
const dog = new Dog("小白", "柯基");
dog.speak(); // 小白汪汪叫
dog.eat(); // 小白在吃东西 \n 小白吃得很开心
dog.fetch(); // 小白接住了球
class Circle {
constructor(radius) {
this._radius = radius;
}
// Getter
get radius() {
return this._radius;
}
// Setter
set radius(value) {
if (value <= 0) {
throw new Error("半径必须大于0");
}
this._radius = value;
}
get diameter() {
return this._radius * 2;
}
get area() {
return Math.PI * this._radius ** 2;
}
get circumference() {
return 2 * Math.PI * this._radius;
}
}
const circle = new Circle(5);
console.log(circle.radius); // 5
console.log(circle.diameter); // 10
console.log(circle.area); // 78.53981633974483
circle.radius = 10; // 使用setter
class MathHelper {
// 静态属性
static PI = 3.141592653589793;
static version = "1.0.0";
// 静态方法
static sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
static average(...numbers) {
return this.sum(...numbers) / numbers.length;
}
// 工厂方法
static createRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
// 使用静态成员
console.log(MathHelper.PI); // 3.141592653589793
console.log(MathHelper.sum(1, 2, 3, 4, 5)); // 15
console.log(MathHelper.average(1, 2, 3)); // 2
// 实例不能访问静态成员
const helper = new MathHelper();
// helper.PI // undefined
// helper.sum() // Error
class BankAccount {
// 私有字段(#开头)
#balance = 0;
#accountNumber;
constructor(accountNumber, initialBalance = 0) {
this.#accountNumber = accountNumber;
this.#balance = initialBalance;
}
// 私有方法
#validateAmount(amount) {
if (amount <= 0) {
throw new Error("金额必须大于0");
}
return true;
}
// 公有方法
deposit(amount) {
this.#validateAmount(amount);
this.#balance += amount;
console.log(`存款成功,当前余额:${this.#balance}`);
}
withdraw(amount) {
this.#validateAmount(amount);
if (amount > this.#balance) {
throw new Error("余额不足");
}
this.#balance -= amount;
console.log(`取款成功,当前余额:${this.#balance}`);
}
getBalance() {
return this.#balance;
}
// 公有getter
get accountNumber() {
return this.#accountNumber;
}
}
const account = new BankAccount("1234567890", 1000);
account.deposit(500); // 存款成功,当前余额:1500
account.withdraw(200); // 取款成功,当前余额:1300
console.log(account.getBalance()); // 1300
// 私有字段外部无法访问
// account.#balance = 10000; // SyntaxError
// console.log(account.#balance); // SyntaxError
// 定义可复用的功能
const CanSwim = {
swim() {
console.log(`${this.name}在游泳`);
},
};
const CanFly = {
fly() {
console.log(`${this.name}在飞翔`);
},
};
const CanRun = {
run() {
console.log(`${this.name}在奔跑`);
},
};
// 组合多个功能
class Animal {
constructor(name) {
this.name = name;
}
}
class Duck extends Animal {
constructor(name) {
super(name);
}
}
// 使用Object.assign混入功能
Object.assign(Duck.prototype, CanSwim, CanFly, CanRun);
const duck = new Duck("唐老鸭");
duck.swim(); // 唐老鸭在游泳
duck.fly(); // 唐老鸭在飞翔
duck.run(); // 唐老鸭在奔跑
// 模拟抽象类
class Shape {
constructor(color) {
if (new.target === Shape) {
throw new Error("Shape类是抽象类,不能直接实例化");
}
this.color = color;
}
// 抽象方法(子类必须实现)
calculateArea() {
throw new Error("子类必须实现calculateArea方法");
}
// 抽象方法(子类必须实现)
calculatePerimeter() {
throw new Error("子类必须实现calculatePerimeter方法");
}
// 具体方法
describe() {
console.log(`这是一个${this.color}的形状`);
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
calculateArea() {
return Math.PI * this.radius ** 2;
}
calculatePerimeter() {
return 2 * Math.PI * this.radius;
}
}
class Rectangle extends Shape {
constructor(color, width, height) {
super(color);
this.width = width;
this.height = height;
}
calculateArea() {
return this.width * this.height;
}
calculatePerimeter() {
return 2 * (this.width + this.height);
}
}
// const shape = new Shape('红色'); // Error
const circle = new Circle("蓝色", 5);
console.log(circle.calculateArea()); // 78.53981633974483
// 简单的装饰器函数
function logged(constructor) {
return class extends constructor {
constructor(...args) {
console.log(`创建 ${constructor.name} 的实例`);
super(...args);
}
};
}
function withTimestamp(constructor) {
constructor.prototype.createdAt = new Date();
}
@logged
@withTimestamp
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const product = new Product("手机", 2999);
// 控制台输出:创建 Product 的实例
console.log(product.createdAt); // 创建时间
class ShoppingCart {
constructor() {
this.items = [];
this.total = 0;
}
addItem(product, quantity = 1) {
const existingItem = this.items.find(item => item.product.id === product.id);
if (existingItem) {
existingItem.quantity += quantity;
} else {
this.items.push({
product,
quantity,
});
}
this.calculateTotal();
}
removeItem(productId, quantity = 1) {
const itemIndex = this.items.findIndex(item => item.product.id === productId);
if (itemIndex !== -1) {
if (this.items[itemIndex].quantity <= quantity) {
this.items.splice(itemIndex, 1);
} else {
this.items[itemIndex].quantity -= quantity;
}
this.calculateTotal();
}
}
calculateTotal() {
this.total = this.items.reduce((sum, item) => {
return sum + item.product.price * item.quantity;
}, 0);
}
clear() {
this.items = [];
this.total = 0;
}
getItemCount() {
return this.items.reduce((count, item) => count + item.quantity, 0);
}
checkout() {
const order = {
items: [...this.items],
total: this.total,
date: new Date(),
};
this.clear();
return order;
}
}
// 使用示例
const cart = new ShoppingCart();
cart.addItem({ id: 1, name: "苹果", price: 5 }, 2);
cart.addItem({ id: 2, name: "香蕉", price: 3 }, 3);
console.log(cart.total); // 19
console.log(cart.getItemCount()); // 5