@@ -1741,24 +1741,37 @@ const car = new Car()
1741
1741
```
1742
1742
** [ ⬆ 返回顶部] ( #代码整洁的-javascript ) **
1743
1743
1744
- ### Prefer composition over inheritance
1744
+ ### 组合优先于继承
1745
1745
As stated famously in [ * Design Patterns* ] ( https://en.wikipedia.org/wiki/Design_Patterns ) by the Gang of Four,
1746
1746
you should prefer composition over inheritance where you can. There are lots of
1747
1747
good reasons to use inheritance and lots of good reasons to use composition.
1748
1748
The main point for this maxim is that if your mind instinctively goes for
1749
1749
inheritance, try to think if composition could model your problem better. In some
1750
1750
cases it can.
1751
1751
1752
+ 正如[ * 设计模式四人帮* ] ( https://en.wikipedia.org/wiki/Design_Patterns ) 所述, 如果可能,
1753
+ 你应该优先使用组合而不是继承。 有许多好的理由去使用继承, 也有许多好的理由去使用组合。这个格言
1754
+ 的重点是, 如果你本能的观点是继承, 那么请想一下组合能否更好的为你的问题建模。 很多情况下它真的
1755
+ 可以。
1756
+
1752
1757
You might be wondering then, "when should I use inheritance?" It
1753
1758
depends on your problem at hand, but this is a decent list of when inheritance
1754
1759
makes more sense than composition:
1755
1760
1761
+ 那么你也许会这样想, “我什么时候改使用继承?” 这取决于你手上的问题, 不过这儿有一个像样的列表说
1762
+ 明什么时候继承比组合更好用:
1763
+
1756
1764
1 . Your inheritance represents an "is-a" relationship and not a "has-a"
1757
1765
relationship (Human->Animal vs. User->UserDetails).
1758
1766
2 . You can reuse code from the base classes (Humans can move like all animals).
1759
1767
3 . You want to make global changes to derived classes by changing a base class.
1760
1768
(Change the caloric expenditure of all animals when they move).
1761
1769
1770
+
1771
+ 1 . 你的继承表示"是一个"的关系而不是"有一个"的关系(人类->动物 vs 用户->用户详情);
1772
+ 2 . 你可以重用来自基类的代码(人可以像所有动物一样行动);
1773
+ 3 . 你想通过基类对子类进行全局的修改(改变所有动物行动时的热量消耗);
1774
+
1762
1775
** Bad:**
1763
1776
``` javascript
1764
1777
class Employee {
0 commit comments