掌握类的基本语法和面向对象编程的核心概念
// 类的定义
class Person {
// 构造函数
constructor(name, age) {
this.name = name;
this.age = age;
}
// 实例方法
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
// 静态方法
static createAdult(name) {
return new Person(name, 18);
}
}
// 创建实例
const john = new Person('John', 30);
console.log(john.greet()); // Hello, my name is John and I am 30 years old.
// 使用静态方法
const adult = Person.createAdult('Jane');
console.log(adult.age); // 18new 关键字调用static 关键字定义// 父类
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return 'Animal sound';
}
}
// 子类
class Dog extends Animal {
constructor(name, breed) {
super(name); // 调用父类构造函数
this.breed = breed;
}
// 重写父类方法
speak() {
return 'Woof!';
}
// 调用父类方法
speakLikeAnimal() {
return super.speak();
}
}
// 创建实例
const dog = new Dog('Buddy', 'Golden Retriever');
console.log(dog.name); // Buddy
console.log(dog.breed); // Golden Retriever
console.log(dog.speak()); // Woof!
console.log(dog.speakLikeAnimal()); // Animal soundclass Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Getter
get fullInfo() {
return `${this.name}, ${this.age} years old`;
}
// Setter
set age(newAge) {
if (newAge >= 0) {
this._age = newAge;
} else {
throw new Error('Age cannot be negative');
}
}
get age() {
return this._age;
}
}
const person = new Person('John', 30);
console.log(person.fullInfo); // John, 30 years old
person.age = 31;
console.log(person.age); // 31class Person {
// 私有字段
#privateField;
constructor(name) {
this.name = name;
this.#privateField = 'private value';
}
// 访问私有字段
getPrivateField() {
return this.#privateField;
}
// 修改私有字段
setPrivateField(value) {
this.#privateField = value;
}
}
const person = new Person('John');
console.log(person.name); // John
console.log(person.#privateField); // 语法错误
console.log(person.getPrivateField()); // private value
person.setPrivateField('new private value');
console.log(person.getPrivateField()); // new private value// 定义装饰器
function log(target, propertyName, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args) {
console.log(`Calling ${propertyName} with ${args}`);
const result = originalMethod.apply(this, args);
console.log(`${propertyName} returned ${result}`);
return result;
};
return descriptor;
}
// 使用装饰器
class Calculator {
@log
add(a, b) {
return a + b;
}
}
const calc = new Calculator();
calc.add(1, 2); // 输出调用和返回信息