js实现一个面向对象
面向对象编程基础
JavaScript 是一种多范式的编程语言,支持面向对象编程(OOP)。通过构造函数、原型链和 ES6 的类语法,可以实现面向对象的特性。
使用构造函数和原型链
构造函数用于创建对象实例,原型链用于共享方法和属性。

function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
const person1 = new Person('Alice', 25);
person1.greet(); // 输出: Hello, my name is Alice and I am 25 years old.
使用 ES6 类语法
ES6 引入了 class 关键字,使面向对象编程更加直观。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person2 = new Person('Bob', 30);
person2.greet(); // 输出: Hello, my name is Bob and I am 30 years old.
继承的实现
通过 extends 关键字实现继承,子类可以继承父类的属性和方法。

class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
console.log(`${this.name} is studying in grade ${this.grade}.`);
}
}
const student1 = new Student('Charlie', 18, 12);
student1.greet(); // 输出: Hello, my name is Charlie and I am 18 years old.
student1.study(); // 输出: Charlie is studying in grade 12.
封装和私有字段
使用 # 前缀定义私有字段,确保数据封装。
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
多态的实现
通过方法重写实现多态,子类可以覆盖父类的方法。
class Animal {
speak() {
console.log('Animal makes a sound');
}
}
class Dog extends Animal {
speak() {
console.log('Dog barks');
}
}
const animal = new Animal();
const dog = new Dog();
animal.speak(); // 输出: Animal makes a sound
dog.speak(); // 输出: Dog barks
以上方法展示了 JavaScript 中实现面向对象编程的多种方式,包括构造函数、原型链、ES6 类语法、继承、封装和多态。






