【JavaScript 】JavaScript 中的面向对象编程
·
JavaScript 中的面向对象编程
JavaScript 支持面向对象编程(OOP),但与其他语言(如 Java 或 C++)不同,它采用基于原型的继承机制而非基于类的继承。以下是 JavaScript 中实现 OOP 的核心概念和方法。
构造函数与 new 关键字
构造函数用于创建对象实例。通过 new 关键字调用构造函数时,JavaScript 会自动创建一个新对象,并将 this 绑定到该对象。
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person("Alice", 25);
console.log(person1.name); // "Alice"
原型(Prototype)
JavaScript 中的每个函数都有一个 prototype 属性,用于共享方法和属性,c4j.kxjzhibo.cn从而避免重复定义。
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
person1.greet(); // "Hello, my name is Alice"
ES6 类语法
ES6 引入了 class 语法糖,arn.zw-gov.cn使 OOP 更接近传统语言风格,但底层仍基于原型。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person2 = new Person("Bob", 30);
person2.greet(); // "Hello, my name is Bob"
继承与 extends
使用 extends 关键字实现继承,eh4.jrsgjzb.com子类可以继承父类的属性和方法。
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
console.log(`${this.name} is studying hard.`);
}
}
const student1 = new Student("Charlie", 20, "A");
student1.greet(); // "Hello, my name is Charlie"
student1.study(); // "Charlie is studying hard."
封装与私有字段
通过 # 前缀定义私有字段,确保外部无法直接访问。
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
// console.log(account.#balance); // 报错:私有字段不可访问
静态方法与属性
使用 static 关键字定义类级别的属性和方法,无需实例化即可调用kis.ktzzhibo.cn。
class MathUtils {
static PI = 3.14159;
static square(x) {
return x * x;
}
}
console.log(MathUtils.PI); // 3.14159
console.log(MathUtils.square(5)); // 25
总结
JavaScript 的 OOP 提供了多种实现方式,从构造函数和原型到 ES6 类语法。通过合理使用继承、封装和静态成员,可以构建模块化且可维护的代码。
更多推荐



所有评论(0)