JavaScript 中的面向对象编程 (OOP):综合指南

来源:undefined 2025-01-20 04:31:06 1028

JavaScript面向对象编程(OOP)指南

类与对象

在JavaScript中,对象是属性(键)和方法(值)的集合。类是创建对象的模板。

例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

// 定义一个类

class Person {

constructor(name, age) {

this.name = name; // 属性

this.age = age;

}

greet() { // 方法

console.log(`你好,我的名字是${this.name},我${this.age}岁了。`);

}

}

// 创建一个对象

const person1 = new Person(Alice, 30);

person1.greet(); // 输出:你好,我的名字是Alice,我30岁了。

登录后复制

封装

封装将数据(属性)及其操作方法捆绑在一个单元(对象)中,限制了对对象内部的直接访问。

例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

class BankAccount {

#balance; // 私有属性

constructor(initialBalance) {

this.#balance = initialBalance;

}

deposit(amount) {

this.#balance += amount;

}

getBalance() {

return this.#balance;

}

}

const account = new BankAccount(1000);

account.deposit(500);

console.log(account.getBalance()); // 1500

// console.log(account.#balance); // 错误:无法访问私有属性 #balance

登录后复制

继承

继承允许一个类继承另一个类的属性和方法,实现代码复用。

立即学习Java免费学习笔记(深入)”;

例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

class Animal {

constructor(name) {

this.name = name;

}

speak() {

console.log(`${this.name} 发出声音。`);

}

}

class Dog extends Animal {

speak() {

console.log(`${this.name} 汪汪叫。`);

}

}

const dog = new Dog(Buddy);

dog.speak(); // 输出:Buddy 汪汪叫。

登录后复制

多态

多态指同一方法在不同类中具有不同实现。

例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

class Shape {

area() {

return 0;

}

}

class Rectangle extends Shape {

constructor(width, height) {

super();

this.width = width;

this.height = height;

}

area() {

return this.width * this.height;

}

}

const shape = new Shape();

const rectangle = new Rectangle(10, 5);

console.log(shape.area());       // 0

console.log(rectangle.area());   // 50

登录后复制

抽象

抽象隐藏了代码的复杂性,只向用户展示必要的部分。

例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

class Vehicle {

startEngine() {

console.log(引擎启动);

}

}

class Car extends Vehicle {

drive() {

console.log(驾驶汽车...);

}

}

const car = new Car();

car.startEngine(); // 引擎启动

car.drive();       // 驾驶汽车...

登录后复制

静态方法和属性

静态方法和属性属于类本身,而不是类的实例。

例子:

1

2

3

4

5

6

7

class MathUtils {

static add(a, b) {

return a + b;

}

}

console.log(MathUtils.add(5, 3)); // 8

登录后复制

原型

JavaScript使用原型继承,对象可以从其他对象继承属性和方法。

例子:

1

2

3

4

5

6

7

8

9

10

function Person(name) {

this.name = name;

}

Person.prototype.greet = function() {

console.log(`你好,我的名字是${this.name}`);

};

const person = new Person(Alice);

person.greet(); // 你好,我的名字是Alice

登录后复制

要点

使用class定义类。 使用#定义私有属性。 使用extends实现继承。 利用多态实现不同类的相同方法的不同行为。 使用抽象简化代码。 使用静态方法和属性。 理解原型继承机制。

JavaScript的OOP特性让开发者编写更清晰、模块化、可复用的代码。

作者:Abhay Singh Kathayat 全栈开发者,精通前后端技术,擅长使用多种编程语言和框架构建高效、可扩展且用户友好的应用。 联系邮箱:kaashshorts28@gmail.com

最新文章