什么是面向对象编程
What is Object-Oriented Programming (OOP)
一句话:把数据和操作数据的方法打包在一起,用对象来组织程序。
四个特征(背下来):
- 封装—— 内部细节藏起来, 只暴露必要的接口。JS 里用闭包或
#private字段实现。 - 继承—— 子类复用父类的能力。
- 多态—— 同一个方法名, 不同对象有不同行为。
- 抽象—— 只关心「能做什么」, 不关心「怎么做的」。
JS 的特别之处(这才是考点):它是基于原型(prototype)的, 不是基于类的。class 是 ES6 加的语法糖, 底下还是原型链 ——class A extends B 编译后就是设置A.prototype.__proto__ = B.prototype。
原型链一句话:访问一个属性时,对象自己没有就去__proto__ 上找, 一层层往上直到 null。和作用域链是一个套路, 只是一个查变量、一个查属性。
会追问:「React 为什么从 class 转向函数组件?」—— 因为 UI 更适合用「输入 → 输出」来描述, 而不是「一个有生命周期的对象」; 而且 class 里 this的绑定问题、逻辑按生命周期而不是按关注点拆分, 都是实际痛点(见 #322)。
In one line: bundle data together with the methods that act on it, and organise the program around objects.
Four pillars — memorise these:
- Encapsulation — hide the internals, expose only the interface callers need. In JS you get it from closures or
#privatefields. - Inheritance — a subclass reuses what the parent can already do.
- Polymorphism — same method name, different behaviour per object.
- Abstraction — you care what it can do, not how it does it.
What makes JS different, and this is the real question: it is prototype-based, not class-based. class is syntax sugar added in ES6; the prototype chain is still underneath — class A extends B compiles down to setting A.prototype.__proto__ = B.prototype.
The prototype chain in one line: read a property, and if the object does not have it the lookup walks up __proto__ one level at a time until null. Same idea as the scope chain — one looks up variables, the other looks up properties.
Follow-up: “Why did React move from classes to function components?” — because UI is easier to describe as “input → output” than as an object with a lifecycle. On top of that, this binding and code split by lifecycle instead of by concern were real, daily pain (see #322).