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

javascript 中的面向对象编程 (oop):综合指南

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

类与对象

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

例子:

// 定义一个类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岁了。

封装

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

例子:

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免费学习笔记(深入)”;

例子:

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 汪汪叫。

多态

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

例子:

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());       // 0console.log(rectangle.area());   // 50

抽象

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

例子:

class Vehicle {  startEngine() {    console.log('引擎启动');  }}class Car extends Vehicle {  drive() {    console.log('驾驶汽车...');  }}const car = new Car();car.startEngine(); // 引擎启动car.drive();       // 驾驶汽车...

静态方法和属性

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

例子:

class MathUtils {  static add(a, b) {    return a + b;  }}console.log(MathUtils.add(5, 3)); // 8

原型

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

例子:

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

以上就是JavaScript 中的面向对象编程 (OOP):综合指南的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1499769.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 22:02:49
下一篇 2025年12月19日 22:02:56

相关推荐

发表回复

登录后才能评论
关注微信