当前位置: 首页 > article >正文

Es6中怎么使用class实现面向对象编程

在 JavaScript 中,面向对象的类可以通过 class 关键字来定义。以下是一个简单的示例,展示了如何定义一个类、创建对象以及添加方法:

基础类定义

// 定义一个类

class MyClass {

  // 构造函数,用于初始化对象的属性

  constructor(param1, param2) {

       this.property1 = param1;

       this.property2 = param2;

  }

  // 方法

  method1() {

    console.log(`Property 1: ${this.property1}`);

  }

  // 另一个方法

  method2() {

    console.log(`Property 2: ${this.property2}`);

  }

}

// 创建对象

const obj = new MyClass('value1', 'value2');

// 调用对象的方法

obj.method1(); // 输出:Property 1: value1

obj.method2(); // 输出:Property 2: value2

- 使用 `class` 关键字定义一个类,类名多用首字母大写的驼峰式命名。

- 类中可以包含构造函数(`constructor`),用于初始化对象的属性,this关键字则代表实例对象obj。

-constructor()方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor()方法,如果没有显式定义,一个空的constructor()方法会被js引擎默认添加。

- 类中的方法定义在类的大括号内,可以使用 `this` 关键字来访问对象的属性。

-定义方法时前面不需要加上function这个关键字,直接把函数定义放进去了就可以了。另外,方法与方法之间不需要逗号分隔,加了会报错。

-类必须使用new调用,否则会报错。

继承

JavaScript 的类支持原型继承,子类可以继承父类的属性和方法。

// 定义一个名为 Student 的子类,继承自 Person 类

class Student extends Person {

    constructor(name, age, studentId) {

        super(name, age);  // 调用父类的构造函数

        this.studentId = studentId; // 子类新增的属性

   }

  // 子类自己的方法

    displayStudentInfo() {

        console.log(`Student ID: ${this.studentId}, Name: ${this.name}, Age: ${this.age}`);

    }

    // 重写父类的方法

    sayHello() {

        console.log(`Hi, I'm ${this.name}, a student with ID: ${this.studentId}`);

    }

}

// 创建 Student 类的实例

const student1 = new Student('Bob', 20, 'S12345');

student1.sayHello(); // 输出:Hi, I'm Bob, a student with ID: S12345

student1.celebrateBirthday(); // 从父类继承的方法,输出:Bob is now 21 years old! student1.displayStudentInfo(); // 输出:Student ID: S12345, Name: Bob, Age: 21

封装

可以通过将属性定义为私有属性来实现封装,防止外部直接访问和修改对象的内部状态。

class BankAccount {

    // 定义私有属性

    #balance;

    constructor(initialBalance) {

        this.#balance = initialBalance;

    }

    // 公共方法用于存款

    deposit(amount) {

        if (amount > 0) {

            this.#balance += amount; console.log(`Deposited $${amount}. New balance: $${this.#balance}`);

        } else {

            console.log('Deposit amount must be positive');

        }

    }

    // 公共方法用于取款

    withdraw(amount) {

        if (amount > 0 && amount <= this.#balance) {

            this.#balance -= amount; console.log(`Withdrew $${amount}. New balance: $${this.#balance}`);

        } else {

            console.log('Invalid withdrawal amount');

        }

    }

    // 提供一个公共方法来获取私有属性的值

    getBalance() {

        return this.#balance;

    }

}

   // 测试 BankAccount 类

   const account = new BankAccount(1000);

   account.deposit(500); // 输出:Deposited $500. New balance: $1500

    ccount.withdraw(200); // 输出:Withdrew $200. New balance: $1300     console.log(account.getBalance()); // 输出:1300 // 尝试直接访问私有属性会报错 //     console.log(account.#balance); // 会在编译时出错

静态属性和方法

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

class MathUtils {

    // 静态属性

    static PI = 3.14159;

     // 静态方法

    static calculateCircleArea(radius) {

        return this.PI * radius * radius;

      }

}

// 使用静态属性和方法,无需创建实例

console.log(MathUtils.PI); // 输出:3.14159

console.log(MathUtils.calculateCircleArea(5)); // 输出:78.53975

Getter 和 Setter

可以使用getter和setter来控制对对象属性的访问和修改。

class Product { constructor(price) {

    this._price = price; // 使用 _ 前缀表示这是一个内部属性

}

// getter 方法

get price() {

    return this._price;

}

// setter 方法

set price(newPrice) {

    if (newPrice > 0) {

        this._price = newPrice;

    } else {

        console.log('Price must be positive');

    }

}

}

// 测试 getter 和 setter

const product = new Product(100);

console.log(product.price); // 使用 getter,输出:100

product.price = 200; // 使用 setter

console.log(product.price); // 输出:200

product.price = -50; // 尝试设置负值,会触发 setter 中的验证逻辑 // 输出:Price must be positive

http://www.lryc.cn/news/2386241.html

相关文章:

  • digitalworld.local: FALL靶场
  • MySQL---库操作
  • 动态规划算法:字符串类问题(2)公共串
  • uni-app(5):Vue3语法基础上
  • 深度解析Vue项目Webpack打包分包策略 从基础配置到高级优化,全面掌握性能优化核心技巧
  • ubuntu下docker安装mongodb-支持单副本集
  • spring-boot-starter-data-redis应用详解
  • 5060显卡驱动PyCUDA开发环境搭建
  • redis搭建最小的集群,3主3从
  • 《帝国时代1》游戏秘籍
  • 【sylar-webserver】10 HTTP模块
  • 攻略生成模块
  • 海康NVR录像回放SDK原始流转FLV视频流:基于Java的流媒体转码(无需安装第三方插件ffmpeg)
  • 深入理解设计模式:工厂模式、单例模式
  • 运维Linux之Ansible详解学习(更新中)
  • 深入浅出IIC协议 - 从总线原理到FPGA实战开发 -- 第三篇:Verilog实现I2C Master核
  • 网络世界的“变色龙“:动态IP如何重构你的数据旅程?
  • 进阶-自定义类型(结构体、位段、枚举、联合)
  • 5G 网络全场景注册方式深度解析:从信令交互到报文分析
  • ARM笔记-嵌入式系统基础
  • 一文讲透golang channel 的特点、原理及使用场景
  • upload-labs通关笔记-第19关文件上传之条件竞争
  • 第5章:任务间通信机制(IPC)全解析
  • CAPL自动化-诊断Demo工程
  • SVN被锁定解决svn is already locked
  • 【深度学习】1. 感知器,MLP, 梯度下降,激活函数,反向传播,链式法则
  • 云原生安全:网络协议TCP详解
  • 使用CentOS部署本地DeekSeek
  • Spring Boot与Eventuate Tram整合:构建可靠的事件驱动型分布式事务
  • Python:从脚本语言到工业级应用的传奇进化