JavaScript 面向对象编程(OOP)是一种编程范式,它使用“对象”来设计应用程序和软件。以下是一个简单的 JavaScript 面向对象编程的示例:
// 定义一个类
class Person {
// 构造函数,用于初始化对象
constructor(name, age) {
this.name = name;
this.age = age;
}
// 方法:介绍自己
introduce() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// 创建对象实例
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
// 调用对象的方法
console.log(person1.introduce()); // 输出: Hello, my name is Alice and I am 30 years old.
console.log(person2.introduce()); // 输出: Hello, my name is Bob and I am 25 years old.
#
前缀,只能在类的内部访问。class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
return `${this.name} is studying in grade ${this.grade}.`;
}
}
const student1 = new Student('Charlie', 15, 9);
console.log(student1.introduce()); // 输出: Hello, my name is Charlie and I am 15 years old.
console.log(student1.study()); // 输出: Charlie is studying in grade 9.
class Counter {
#count = 0;
increment() {
this.#count++;
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 输出: 1
console.log(counter.#count); // 报错: SyntaxError: Private field '#count' must be declared in an enclosing class
通过这些示例和解释,你应该能够理解 JavaScript 中面向对象编程的基础概念、优势、类型、应用场景以及常见问题的解决方法。
领取专属 10元无门槛券
手把手带您无忧上云