我的 React 之旅:第 15 天

我的 react 之旅:第 15 天

面向对象编程(oop)
面向对象编程是一种基于对象概念的编程范式。

面向对象编程的关键原则
1.封装:

将相关变量和函数分组到一个对象中。鼓励减少函数中的参数,降低复杂性。例子:

function circle(radius) {    this.radius = radius;    this.draw = function() {        console.log('draw');    };}const circle = new circle(5);console.log(circle.radius); // access encapsulated propertycircle.draw(); // call encapsulated method

2.摘要:

隐藏细节和复杂性,仅暴露对象的必要部分。
简化界面并减少底层代码更改的影响。
示例:抽象方法,同时隐藏内部逻辑。

3.继承:

允许一个类(子类)继承另一个类(父类)的属性和方法。
减少冗余代码。
示例:

class animal {    eat() {        console.log("this animal is eating.");    }}class dog extends animal {    bark() {        console.log("the dog is barking.");    }}const dog = new dog();dog.eat(); // inherited from animaldog.bark();

4.多态性:

指具有多种形式的物体。
允许为不同的对象类型提供统一的接口,从而实现代码重用和灵活性。
示例:

class animal {    sound() {        console.log("this animal makes a sound.");    }}class dog extends animal {    sound() {        console.log("the dog barks.");    }}const animal = new animal();const dog = new dog();animal.sound(); // output: this animal makes a sound.dog.sound();    // output: the dog barks.

oop 的重要性

封装:降低复杂性并增强可重用性。抽象:隐藏实现细节,简化交互。继承:消除代码重复并促进重用。多态性:实现灵活性和简化的代码结构。

实际例子
类和构造函数

以结构化、简洁的方式创建对象。示例:

class product {    constructor(name, price) {        this.name = name;        this.price = price;    }    displayproduct() {        console.log(`product: ${this.name}`);        console.log(`price: $${this.price.tofixed(2)}`);    }    calculatetotal(salestax) {        return this.price + this.price * salestax;    }}const product1 = new product("laptop", 1200);product1.displayproduct();console.log(`total price: $${product1.calculatetotal(0.1).tofixed(2)}`);

与动物的传承

展示可重用性和方法重写。示例:

class Animal {    eat() {        console.log("This animal eats food.");    }}class Bird extends Animal {    fly() {        console.log("This bird can fly.");    }}const bird = new Bird();bird.eat();bird.fly();

反思
我学到了什么:

核心 oop 原则:封装、抽象、继承、多态性。降低代码复杂性和增强可重用性的实际用例。应用构造函数、方法和继承来解决现实世界的问题。

oop 是另一个层次。

明天我们再去!

以上就是我的 React 之旅:第 15 天的详细内容,更多请关注创想鸟其它相关文章!

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

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 21:44:51
下一篇 2025年12月19日 21:45:02

相关推荐

发表回复

登录后才能评论
关注微信