面向对象编程(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 property circle.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 animal dog.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 是另一个层次。
明天我们再去!