
面向对象编程(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 原则:封装、抽象、继承、多态性。
- 降低代码复杂性和增强可重用性的实际用例。
- 应用构造函数、方法和继承来解决现实世界的问题。
oop 是另一个层次。
明天我们再去!








