js实现一个面向对象
面向对象编程基础
JavaScript 是一种基于原型的面向对象语言,可以通过构造函数、原型链以及 ES6 的 class 语法实现面向对象编程。
使用构造函数和原型链
通过构造函数定义对象的属性和方法,原型链用于共享方法以减少内存占用。
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 的 class 语法
ES6 引入了 class 关键字,使面向对象编程更接近传统语言(如 Java 或 C++)。
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 person1 = new Person("Bob", 30);
person1.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.
封装与访问控制
JavaScript 本身没有严格的私有成员支持,但可以通过闭包或 Symbol 实现类似效果。
class BankAccount {
constructor(balance) {
let _balance = balance; // 私有变量
this.getBalance = function() {
return _balance;
};
this.deposit = function(amount) {
_balance += amount;
};
}
}
const account = new BankAccount(1000);
console.log(account.getBalance()); // 输出: 1000
account.deposit(500);
console.log(account.getBalance()); // 输出: 1500
多态的实现
多态通过方法重写实现,子类可以覆盖父类的方法。
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
静态方法与属性
静态方法和属性属于类本身,而不是实例。
class MathUtils {
static PI = 3.14159;
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.PI); // 输出: 3.14159
console.log(MathUtils.add(2, 3)); // 输出: 5





