A place to cache linked articles (think custom and personal wayback machine)
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

index.html 58KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <!doctype html><!-- This is a valid HTML5 document. -->
  2. <!-- Screen readers, SEO, extensions and so on. -->
  3. <html lang=fr>
  4. <!-- Has to be within the first 1024 bytes, hence before the <title>
  5. See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
  6. <meta charset=utf-8>
  7. <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
  8. <!-- The viewport meta is quite crowded and we are responsible for that.
  9. See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
  10. <meta name=viewport content="width=device-width,minimum-scale=1,initial-scale=1,shrink-to-fit=no">
  11. <!-- Required to make a valid HTML5 document. -->
  12. <title>Common Misconceptions About Inheritance in JavaScript (archive) — David Larlet</title>
  13. <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
  14. <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons/apple-touch-icon.png">
  15. <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons/favicon-32x32.png">
  16. <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons/favicon-16x16.png">
  17. <link rel="manifest" href="/manifest.json">
  18. <link rel="mask-icon" href="/static/david/icons/safari-pinned-tab.svg" color="#5bbad5">
  19. <link rel="shortcut icon" href="/static/david/icons/favicon.ico">
  20. <meta name="apple-mobile-web-app-title" content="David Larlet">
  21. <meta name="application-name" content="David Larlet">
  22. <meta name="msapplication-TileColor" content="#da532c">
  23. <meta name="msapplication-config" content="/static/david/icons/browserconfig.xml">
  24. <meta name="theme-color" content="#f0f0ea">
  25. <!-- That good ol' feed, subscribe :p. -->
  26. <link rel=alternate type="application/atom+xml" title=Feed href="/david/log/">
  27. <meta name="robots" content="noindex, nofollow">
  28. <meta content="origin-when-cross-origin" name="referrer">
  29. <!-- Canonical URL for SEO purposes -->
  30. <link rel="canonical" href="https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a">
  31. <style>
  32. /* http://meyerweb.com/eric/tools/css/reset/ */
  33. html, body, div, span,
  34. h1, h2, h3, h4, h5, h6, p, blockquote, pre,
  35. a, abbr, address, big, cite, code,
  36. del, dfn, em, img, ins,
  37. small, strike, strong, tt, var,
  38. dl, dt, dd, ol, ul, li,
  39. fieldset, form, label, legend,
  40. table, caption, tbody, tfoot, thead, tr, th, td,
  41. article, aside, canvas, details, embed,
  42. figure, figcaption, footer, header, hgroup,
  43. menu, nav, output, ruby, section, summary,
  44. time, mark, audio, video {
  45. margin: 0;
  46. padding: 0;
  47. border: 0;
  48. font-size: 100%;
  49. font: inherit;
  50. vertical-align: baseline;
  51. }
  52. /* HTML5 display-role reset for older browsers */
  53. article, aside, details, figcaption, figure,
  54. footer, header, hgroup, menu, nav, section { display: block; }
  55. body { line-height: 1; }
  56. blockquote, q { quotes: none; }
  57. blockquote:before, blockquote:after,
  58. q:before, q:after {
  59. content: '';
  60. content: none;
  61. }
  62. table {
  63. border-collapse: collapse;
  64. border-spacing: 0;
  65. }
  66. /* http://practicaltypography.com/equity.html */
  67. /* https://calendar.perfplanet.com/2016/no-font-face-bulletproof-syntax/ */
  68. /* https://www.filamentgroup.com/lab/js-web-fonts.html */
  69. @font-face {
  70. font-family: 'EquityTextB';
  71. src: url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff2') format('woff2'),
  72. url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff') format('woff');
  73. font-weight: 300;
  74. font-style: normal;
  75. font-display: swap;
  76. }
  77. @font-face {
  78. font-family: 'EquityTextB';
  79. src: url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff2') format('woff2'),
  80. url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff') format('woff');
  81. font-weight: 300;
  82. font-style: italic;
  83. font-display: swap;
  84. }
  85. @font-face {
  86. font-family: 'EquityTextB';
  87. src: url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff2') format('woff2'),
  88. url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff') format('woff');
  89. font-weight: 700;
  90. font-style: normal;
  91. font-display: swap;
  92. }
  93. @font-face {
  94. font-family: 'ConcourseT3';
  95. src: url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff2') format('woff2'),
  96. url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff') format('woff');
  97. font-weight: 300;
  98. font-style: normal;
  99. font-display: swap;
  100. }
  101. /* http://practice.typekit.com/lesson/caring-about-opentype-features/ */
  102. body {
  103. /* http://www.cssfontstack.com/ Palatino 99% Win 86% Mac */
  104. font-family: "EquityTextB", Palatino, serif;
  105. background-color: #f0f0ea;
  106. color: #07486c;
  107. font-kerning: normal;
  108. -moz-osx-font-smoothing: grayscale;
  109. -webkit-font-smoothing: subpixel-antialiased;
  110. text-rendering: optimizeLegibility;
  111. font-variant-ligatures: common-ligatures contextual;
  112. font-feature-settings: "kern", "liga", "clig", "calt";
  113. }
  114. pre, code, kbd, samp, var, tt {
  115. font-family: 'TriplicateT4c', monospace;
  116. }
  117. em {
  118. font-style: italic;
  119. color: #323a45;
  120. }
  121. strong {
  122. font-weight: bold;
  123. color: black;
  124. }
  125. nav {
  126. background-color: #323a45;
  127. color: #f0f0ea;
  128. display: flex;
  129. justify-content: space-around;
  130. padding: 1rem .5rem;
  131. }
  132. nav:last-child {
  133. border-bottom: 1vh solid #2d7474;
  134. }
  135. nav a {
  136. color: #f0f0ea;
  137. }
  138. nav abbr {
  139. border-bottom: 1px dotted white;
  140. }
  141. h1 {
  142. border-top: 1vh solid #2d7474;
  143. border-bottom: .2vh dotted #2d7474;
  144. background-color: #e3e1e1;
  145. color: #323a45;
  146. text-align: center;
  147. padding: 5rem 0 4rem 0;
  148. width: 100%;
  149. font-family: 'ConcourseT3';
  150. display: flex;
  151. flex-direction: column;
  152. }
  153. h1.single {
  154. padding-bottom: 10rem;
  155. }
  156. h1 span {
  157. position: absolute;
  158. top: 1vh;
  159. left: 20%;
  160. line-height: 0;
  161. }
  162. h1 span a {
  163. line-height: 1.7;
  164. padding: 1rem 1.2rem .6rem 1.2rem;
  165. border-radius: 0 0 6% 6%;
  166. background: #2d7474;
  167. font-size: 1.3rem;
  168. color: white;
  169. text-decoration: none;
  170. }
  171. h2 {
  172. margin: 4rem 0 1rem;
  173. border-top: .2vh solid #2d7474;
  174. padding-top: 1vh;
  175. }
  176. h3 {
  177. text-align: center;
  178. margin: 3rem 0 .75em;
  179. }
  180. hr {
  181. height: .4rem;
  182. width: .4rem;
  183. border-radius: .4rem;
  184. background: #07486c;
  185. margin: 2.5rem auto;
  186. }
  187. time {
  188. display: bloc;
  189. margin-left: 0 !important;
  190. }
  191. ul, ol {
  192. margin: 2rem;
  193. }
  194. ul {
  195. list-style-type: square;
  196. }
  197. a {
  198. text-decoration-skip-ink: auto;
  199. text-decoration-thickness: 0.05em;
  200. text-underline-offset: 0.09em;
  201. }
  202. article {
  203. max-width: 50rem;
  204. display: flex;
  205. flex-direction: column;
  206. margin: 2rem auto;
  207. }
  208. article.single {
  209. border-top: .2vh dotted #2d7474;
  210. margin: -6rem auto 1rem auto;
  211. background: #f0f0ea;
  212. padding: 2rem;
  213. }
  214. article p:last-child {
  215. margin-bottom: 1rem;
  216. }
  217. p {
  218. padding: 0 .5rem;
  219. margin-left: 3rem;
  220. }
  221. p + p,
  222. figure + p {
  223. margin-top: 2rem;
  224. }
  225. blockquote {
  226. background-color: #e3e1e1;
  227. border-left: .5vw solid #2d7474;
  228. display: flex;
  229. flex-direction: column;
  230. align-items: center;
  231. padding: 1rem;
  232. margin: 1.5rem;
  233. }
  234. blockquote cite {
  235. font-style: italic;
  236. }
  237. blockquote p {
  238. margin-left: 0;
  239. }
  240. figure {
  241. border-top: .2vh solid #2d7474;
  242. background-color: #e3e1e1;
  243. text-align: center;
  244. padding: 1.5rem 0;
  245. margin: 1rem 0 0;
  246. font-size: 1.5rem;
  247. width: 100%;
  248. }
  249. figure img {
  250. max-width: 250px;
  251. max-height: 250px;
  252. border: .5vw solid #323a45;
  253. padding: 1px;
  254. }
  255. figcaption {
  256. padding: 1rem;
  257. line-height: 1.4;
  258. }
  259. aside {
  260. display: flex;
  261. flex-direction: column;
  262. background-color: #e3e1e1;
  263. padding: 1rem 0;
  264. border-bottom: .2vh solid #07486c;
  265. }
  266. aside p {
  267. max-width: 50rem;
  268. margin: 0 auto;
  269. }
  270. /* https://fvsch.com/code/css-locks/ */
  271. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  272. font-size: 1rem;
  273. line-height: calc( 1.5em + 0.2 * 1rem );
  274. }
  275. h1 {
  276. font-size: 1.9rem;
  277. line-height: calc( 1.2em + 0.2 * 1rem );
  278. }
  279. h2 {
  280. font-size: 1.6rem;
  281. line-height: calc( 1.3em + 0.2 * 1rem );
  282. }
  283. h3 {
  284. font-size: 1.35rem;
  285. line-height: calc( 1.4em + 0.2 * 1rem );
  286. }
  287. @media (min-width: 20em) {
  288. /* The (100vw - 20rem) / (50 - 20) part
  289. resolves to 0-1rem, depending on the
  290. viewport width (between 20em and 50em). */
  291. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  292. font-size: calc( 1rem + .6 * (100vw - 20rem) / (50 - 20) );
  293. line-height: calc( 1.5em + 0.2 * (100vw - 50rem) / (20 - 50) );
  294. margin-left: 0;
  295. }
  296. h1 {
  297. font-size: calc( 1.9rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  298. line-height: calc( 1.2em + 0.2 * (100vw - 50rem) / (20 - 50) );
  299. }
  300. h2 {
  301. font-size: calc( 1.5rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  302. line-height: calc( 1.3em + 0.2 * (100vw - 50rem) / (20 - 50) );
  303. }
  304. h3 {
  305. font-size: calc( 1.35rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  306. line-height: calc( 1.4em + 0.2 * (100vw - 50rem) / (20 - 50) );
  307. }
  308. }
  309. @media (min-width: 50em) {
  310. /* The right part of the addition *must* be a
  311. rem value. In this example we *could* change
  312. the whole declaration to font-size:2.5rem,
  313. but if our baseline value was not expressed
  314. in rem we would have to use calc. */
  315. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  316. font-size: calc( 1rem + .6 * 1rem );
  317. line-height: 1.5em;
  318. }
  319. p, li, pre, details {
  320. margin-left: 3rem;
  321. }
  322. h1 {
  323. font-size: calc( 1.9rem + 1.5 * 1rem );
  324. line-height: 1.2em;
  325. }
  326. h2 {
  327. font-size: calc( 1.5rem + 1.5 * 1rem );
  328. line-height: 1.3em;
  329. }
  330. h3 {
  331. font-size: calc( 1.35rem + 1.5 * 1rem );
  332. line-height: 1.4em;
  333. }
  334. figure img {
  335. max-width: 500px;
  336. max-height: 500px;
  337. }
  338. }
  339. figure.unsquared {
  340. margin-bottom: 1.5rem;
  341. }
  342. figure.unsquared img {
  343. height: inherit;
  344. }
  345. @media print {
  346. body { font-size: 100%; }
  347. a:after { content: " (" attr(href) ")"; }
  348. a, a:link, a:visited, a:after {
  349. text-decoration: underline;
  350. text-shadow: none !important;
  351. background-image: none !important;
  352. background: white;
  353. color: black;
  354. }
  355. abbr[title] { border-bottom: 0; }
  356. abbr[title]:after { content: " (" attr(title) ")"; }
  357. img { page-break-inside: avoid; }
  358. @page { margin: 2cm .5cm; }
  359. h1, h2, h3 { page-break-after: avoid; }
  360. p3 { orphans: 3; widows: 3; }
  361. img {
  362. max-width: 250px !important;
  363. max-height: 250px !important;
  364. }
  365. nav, aside { display: none; }
  366. }
  367. ul.with_columns {
  368. column-count: 1;
  369. }
  370. @media (min-width: 20em) {
  371. ul.with_columns {
  372. column-count: 2;
  373. }
  374. }
  375. @media (min-width: 50em) {
  376. ul.with_columns {
  377. column-count: 3;
  378. }
  379. }
  380. ul.with_two_columns {
  381. column-count: 1;
  382. }
  383. @media (min-width: 20em) {
  384. ul.with_two_columns {
  385. column-count: 1;
  386. }
  387. }
  388. @media (min-width: 50em) {
  389. ul.with_two_columns {
  390. column-count: 2;
  391. }
  392. }
  393. .gallery {
  394. display: flex;
  395. flex-wrap: wrap;
  396. justify-content: space-around;
  397. }
  398. .gallery figure img {
  399. margin-left: 1rem;
  400. margin-right: 1rem;
  401. }
  402. .gallery figure figcaption {
  403. font-family: 'ConcourseT3'
  404. }
  405. footer {
  406. font-family: 'ConcourseT3';
  407. display: flex;
  408. flex-direction: column;
  409. border-top: 3px solid white;
  410. padding: 4rem 0;
  411. background-color: #07486c;
  412. color: white;
  413. }
  414. footer > * {
  415. max-width: 50rem;
  416. margin: 0 auto;
  417. }
  418. footer a {
  419. color: #f1c40f;
  420. }
  421. footer .avatar {
  422. width: 200px;
  423. height: 200px;
  424. border-radius: 50%;
  425. float: left;
  426. -webkit-shape-outside: circle();
  427. shape-outside: circle();
  428. margin-right: 2rem;
  429. padding: 2px 5px 5px 2px;
  430. background: white;
  431. border-left: 1px solid #f1c40f;
  432. border-top: 1px solid #f1c40f;
  433. border-right: 5px solid #f1c40f;
  434. border-bottom: 5px solid #f1c40f;
  435. }
  436. </style>
  437. <h1>
  438. <span><a id="jumper" href="#jumpto" title="Un peu perdu ?">?</a></span>
  439. Common Misconceptions About Inheritance in JavaScript (archive)
  440. <time>Pour la pérennité des contenus liés. Non-indexé, retrait sur simple email.</time>
  441. </h1>
  442. <section>
  443. <article>
  444. <h3><a href="https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a">Source originale du contenu</a></h3>
  445. <h3 name="5b94" id="5b94" class="graf--h3 graf--first">Aren’t classical inheritance and prototypal inheritance really the same thing, just a stylistic preference?</h3>
  446. <blockquote name="a737" id="a737" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote>
  447. <p name="3db3" id="3db3" class="graf--p">Classical and prototypal inheritance are <strong class="markup--strong markup--p-strong">fundamentally and semantically distinct.</strong></p>
  448. <p name="b561" id="b561" class="graf--p">There are some <strong class="markup--strong markup--p-strong">defining characteristics</strong> between classical inheritance and prototypal inheritance. For any of this article to make sense, you must keep these points in mind:</p>
  449. <p name="9e70" id="9e70" class="graf--p">In <strong class="markup--strong markup--p-strong">class inheritance, instances inherit from a blueprint</strong> (the class), and <strong class="markup--strong markup--p-strong">create sub-class relationships</strong>. In other words, you can’t use the class like you would use an instance. <strong class="markup--strong markup--p-strong">You can’t invoke instance methods on a class definition itself.</strong> You must first create an instance and then invoke methods on that instance.</p>
  450. <p name="007b" id="007b" class="graf--p">In prototypal inheritance, <strong class="markup--strong markup--p-strong">instances inherit from other instances. </strong>Using <strong class="markup--strong markup--p-strong">delegate prototypes</strong> (setting the prototype of one instance to refer to an <strong class="markup--strong markup--p-strong">examplar object</strong>), it’s literally <strong class="markup--strong markup--p-strong">Objects Linking to Other Objects</strong>, or <strong class="markup--strong markup--p-strong">OLOO</strong>, as Kyle Simpson calls it. Using <strong class="markup--strong markup--p-strong">concatenative inheritance</strong>, you just <strong class="markup--strong markup--p-strong">copy properties</strong> from an <strong class="markup--strong markup--p-strong">exemplar object</strong> to a new instance.</p>
  451. <p name="1588" id="1588" class="graf--p">It’s really important that you understand these differences. Class inheritance by virtue of its mechanisms <strong class="markup--strong markup--p-strong">create class hierarchies as a side-effect of sub-class creation.</strong> Those hierarchies lead to <strong class="markup--strong markup--p-strong">arthritic code</strong> (hard to change) and <strong class="markup--strong markup--p-strong">brittleness</strong> (easy to break due to rippling side-effects when you modify base classes).</p>
  452. <p name="fdfd" id="fdfd" class="graf--p">Prototypal inheritance does not necessarily create similar hierarchies. I recommend that you keep prototype chains as shallow as possible. It’s easy to flatten many prototypes together to form a <strong class="markup--strong markup--p-strong">single delegate prototype.</strong></p>
  453. <p name="010c" id="010c" class="graf--p">TL;DR:</p>
  454. <ul class="postList"><li name="ea51" id="ea51" class="graf--li">A <strong class="markup--strong markup--li-strong">class </strong>is a <strong class="markup--strong markup--li-strong">blueprint</strong>.</li><li name="9b8b" id="9b8b" class="graf--li">A <strong class="markup--strong markup--li-strong">prototype</strong> is an <strong class="markup--strong markup--li-strong">object</strong> instance.</li></ul>
  455. <p name="3900" id="3900" class="graf--p graf--empty"><br/></p>
  456. <h3 name="7dea" id="7dea" class="graf--h3">Aren’t classes the right way to create objects in JavaScript?</h3>
  457. <blockquote name="7676" id="7676" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote>
  458. <p name="308b" id="308b" class="graf--p">There are several <strong class="markup--strong markup--p-strong">right ways</strong> to create objects in JavaScript. The first and most common is an object literal. It looks like this (in ES6):</p>
  459. <figure name="22d1" id="22d1" class="graf--figure graf--iframe"><p class="iframeContainer"/></figure>
  460. <p name="a6f1" id="a6f1" class="graf--p">Of course, object literals have been around a lot longer than ES6, but they lack the method shortcut seen above, and you have to use <em class="markup--em markup--p-em">`var`</em> instead of <em class="markup--em markup--p-em">`let`</em>. Oh, and that template string thing in the <em class="markup--em markup--p-em">`.describe()`</em> method won’t work in ES5, either.</p>
  461. <p name="281b" id="281b" class="graf--p">You can attach delegate prototypes with <em class="markup--em markup--p-em">`Object.create()`</em> (an ES5 feature):</p>
  462. <figure name="b75a" id="b75a" class="graf--figure graf--iframe"><p class="iframeContainer"/></figure>
  463. <p name="779b" id="779b" class="graf--p">Let’s break this one down a little. <em class="markup--em markup--p-em">`animal`</em> is a <strong class="markup--strong markup--p-strong">delegate prototype</strong>. <em class="markup--em markup--p-em">`mouse`</em> is an instance. When you try to access a property on <em class="markup--em markup--p-em">`mouse` </em>that isn’t there, the JavaScript runtime will look for the property on <em class="markup--em markup--p-em">`animal`</em> (the delegate).</p>
  464. <p name="3b5c" id="3b5c" class="graf--p"><strong class="markup--strong markup--p-strong"><em class="markup--em markup--p-em">`Object.assign()`</em></strong> is a new ES6 feature championed by Rick Waldron that was previously implemented in a few dozen libraries. You might know it as <em class="markup--em markup--p-em">`$.extend()`</em> from jQuery or <em class="markup--em markup--p-em">`_.extend()`</em> from Underscore. Lodash has a version of it called <em class="markup--em markup--p-em">`assign()`. </em>You pass in a destination object, and as many source objects as you like, separated by commas. It will copy all of the <strong class="markup--strong markup--p-strong">enumerable own properties</strong> by <em class="markup--em markup--p-em">assignment</em> from the source objects to the destination objects with <strong class="markup--strong markup--p-strong">last in priority. </strong>If there are any property name conflicts, the version from the last object passed in wins.</p>
  465. <p name="3182" id="3182" class="graf--p"><strong class="markup--strong markup--p-strong"><em class="markup--em markup--p-em">`Object.create()`</em></strong> is an ES5 feature that was championed by Douglas Crockford so that we could attach delegate prototypes without using constructors and the <em class="markup--em markup--p-em">`new`</em> keyword.</p>
  466. <p name="1398" id="1398" class="graf--p">I’m skipping the constructor function example because I can’t recommend them. I’ve seen them abused a lot, and I’ve seen them cause <a href="https://medium.com/javascript-scene/how-to-fix-the-es6-class-keyword-2d42bb3f4caf" data-href="https://medium.com/javascript-scene/how-to-fix-the-es6-class-keyword-2d42bb3f4caf" class="markup--anchor markup--p-anchor">a lot of trouble</a>. It’s worth noting that a lot of smart people disagree with me. Smart people will do whatever they want.</p>
  467. <p name="6ab7" id="6ab7" class="graf--p">Wise people will <strong class="markup--strong markup--p-strong">take Douglas Crockford’s advice:</strong></p>
  468. <blockquote name="0516" id="0516" class="graf--blockquote graf--startsWithDoubleQuote">“If a feature is sometimes dangerous, and there is a better option, then always use the better option.”</blockquote>
  469. <p name="5b0a" id="5b0a" class="graf--p graf--empty"><br/></p>
  470. <h3 name="1be0" id="1be0" class="graf--h3">Don’t you need a constructor function to specify object instantiation behavior and handle object initialization?</h3>
  471. <blockquote name="94ac" id="94ac" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote>
  472. <p name="a551" id="a551" class="graf--p">Any function can create and return objects. When it’s not a constructor function, it’s called a <strong class="markup--strong markup--p-strong">factory function.</strong></p>
  473. <h4 name="020a" id="020a" class="graf--h4">The Better Option</h4>
  474. <figure name="39dd" id="39dd" class="graf--figure graf--iframe"><p class="iframeContainer"/></figure>
  475. <p name="122a" id="122a" class="graf--p">I usually don’t name my factories “factory” — that’s just for illustration. Normally I just would have called it <em class="markup--em markup--p-em">`mouse()`.</em></p>
  476. <p name="79ff" id="79ff" class="graf--p graf--empty"><br/></p>
  477. <h3 name="b76c" id="b76c" class="graf--h3">Don’t you need constructor functions for privacy in JavaScript?</h3>
  478. <blockquote name="2e4b" id="2e4b" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote>
  479. <p name="239a" id="239a" class="graf--p">In JavaScript, any time you export a function, that function has access to the outer function’s variables. When you use them, the JS engine creates a <strong class="markup--strong markup--p-strong">closure</strong>. Closures are a common pattern in JavaScript, and they’re commonly used for data privacy.</p>
  480. <p name="0d1d" id="0d1d" class="graf--p">Closures are not unique to constructor functions. Any function can create a closure for data privacy:</p>
  481. <figure name="9675" id="9675" class="graf--figure graf--iframe"><p class="iframeContainer"/></figure>
  482. <figure name="c55d" id="c55d" class="graf--figure"><div class="aspectRatioPlaceholder is-locked"><p class="aspect-ratio-fill"/><img class="graf-image" data-image-id="1*PZMdDrJu--I-WSKbrJL7Nw.jpeg" data-width="640" data-height="537" src="https://d262ilb51hltx0.cloudfront.net/max/800/1*PZMdDrJu--I-WSKbrJL7Nw.jpeg"/></div></figure>
  483. <p name="bcc9" id="bcc9" class="graf--p graf--empty"><br/></p>
  484. <h3 name="2969" id="2969" class="graf--h3">Does `new` mean that code is using classical inheritance?</h3>
  485. <blockquote name="7358" id="7358" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote>
  486. <p name="6db2" id="6db2" class="graf--p">The `<em class="markup--em markup--p-em">new`</em> keyword is used to invoke a constructor. What it actually does is:</p>
  487. <ul class="postList"><li name="64cf" id="64cf" class="graf--li">Create a new instance</li><li name="bc9c" id="bc9c" class="graf--li">Bind `<em class="markup--em markup--li-em">this`</em> to the new instance</li><li name="6b68" id="6b68" class="graf--li">Reference the new object’s delegate [[Prototype]] to the object referenced by the constructor function’s <em class="markup--em markup--li-em">`prototype`</em> property.</li><li name="46ad" id="46ad" class="graf--li">Names the object type after the constructor, which you’ll notice mostly in the debugging console. You’ll see `<em class="markup--em markup--li-em">[Object Foo]`,</em> for example, instead of `<em class="markup--em markup--li-em">[Object object]`.</em></li><li name="06b5" id="06b5" class="graf--li">Allows `<em class="markup--em markup--li-em">instanceof`</em> to check whether or not an object’s prototype reference is the same object referenced by the <em class="markup--em markup--li-em">.prototype</em> property of the constructor.</li></ul>
  488. <h4 name="b7d3" id="b7d3" class="graf--h4"><em class="markup--em markup--h4-em">`instanceof`</em> lies</h4>
  489. <p name="e697" id="e697" class="graf--p graf--empty"><br/></p>
  490. <p name="0484" id="0484" class="graf--p">Let’s pause here for a moment and reconsider the value of <em class="markup--em markup--p-em">`instanceof`</em>. You might change your mind about its usefulness.</p>
  491. <p name="6f8c" id="6f8c" class="graf--p"><strong class="markup--strong markup--p-strong">Important:</strong> `<em class="markup--em markup--p-em">instanceof`</em> does not do type checking the way that you expect similar checks to do in strongly typed languages. Instead, it does an identity check on the prototype object, and it’s easily fooled. It won’t work across execution contexts, for instance (a common source of bugs, frustration, and unnecessary limitations). For reference, an <a href="https://github.com/baconjs/bacon.js/issues/296" data-href="https://github.com/baconjs/bacon.js/issues/296" class="markup--anchor markup--p-anchor" rel="nofollow">example in the wild, from bacon.js</a>.</p>
  492. <p name="7565" id="7565" class="graf--p">It’s also easily tricked into false positives (and more commonly) false negatives from another source. Since it’s an identity check against a target object’s `<em class="markup--em markup--p-em">.prototype`</em> property, it can lead to strange things:</p>
  493. <pre name="597b" id="597b" class="graf--pre">&gt; function foo() {}<br/>&gt; var bar = { a: ‘a’};<br/>&gt; foo.prototype = bar; // Object {a: “a”}<br/>&gt; baz = Object.create(bar); // Object {a: “a”}<br/>&gt; baz instanceof foo // true. oops.</pre>
  494. <p name="b4e1" id="b4e1" class="graf--p">That last result is completely in line with the JavaScript specification. Nothing is broken — it’s just that <em class="markup--em markup--p-em">`instanceof`</em> can’t make any guarantees about type safety. <strong class="markup--strong markup--p-strong">It’s easily tricked</strong> into reporting both <strong class="markup--strong markup--p-strong">false positives</strong>, and <strong class="markup--strong markup--p-strong">false negatives</strong>.</p>
  495. <p name="3a80" id="3a80" class="graf--p">Besides that, trying to force your JS code to behave like strongly typed code can block your functions from being lifted to generics, which are much more reusable and useful.</p>
  496. <p name="b6c7" id="b6c7" class="graf--p graf--last"><strong class="markup--strong markup--p-strong">`<em class="markup--em markup--p-em">instanceof</em>` limits the reusability of your code, and potentially introduces bugs into the programs that use your code.</strong></p>
  497. <blockquote name="fea2" id="fea2" class="graf--pullquote pullquote graf--first">`instanceof` lies.</blockquote>
  498. <blockquote name="b9a1" id="b9a1" class="graf--pullquote pullquote graf--last">Ducktype instead.</blockquote>
  499. <p></div></div></section><section name="a7c1" class=" section--content"><div class="section-divider layoutSingleColumn"><hr class="section-divider"></div><div class="section-content"><div class="section-inner layoutSingleColumn"><h4 name="a10b" id="a10b" class="graf--h4 graf--first"><code>new</code> is weird</h4><p name="e4fa" id="e4fa" class="graf--p graf--empty"><br></p><p name="ec06" id="ec06" class="graf--p"><strong class="markup--strong markup--p-strong">WAT?</strong> <code>&lt;em class="markup--em markup--p-em"&gt;new&lt;/em&gt;</code> also does some <em class="markup--em markup--p-em">weird stuff</em> to return values. If you try to return a primitive, it won’t work. If you return any other arbitrary object, that <strong class="markup--strong markup--p-strong"><em class="markup--em markup--p-em">does</em></strong> work, but <em class="markup--em markup--p-em"><code>this</code></em> gets thrown away, breaking all references to it (including <code>&lt;em class="markup--em markup--p-em"&gt;.call()</code></em> and <code>&lt;em class="markup--em markup--p-em"&gt;.apply()</code></em>), and breaking the link to the constructor’s <em class="markup--em markup--p-em"><code>.prototype</code></em> reference.</p><h4 name="646d" id="646d" class="graf--h4 graf--empty"><br></h4><p name="01d4" id="01d4" class="graf--p graf--empty"><br></p><h3 name="68b2" id="68b2" class="graf--h3">Is There a Big Performance Difference Between Classical and Prototypal Inheritance?</h3><blockquote name="422f" id="422f" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote><p name="febe" id="febe" class="graf--p">You may have heard of <strong class="markup--strong markup--p-strong">hidden classes, </strong>and think that constructors dramatically outperform objects instantiated with <em class="markup--em markup--p-em"><code>Object.create()</code></em>. Those performance differences are <strong class="markup--strong markup--p-strong">dramatically overstated.</strong></p><p name="e5e4" id="e5e4" class="graf--p">A small fraction of your application’s time is spent running JavaScript, and a miniscule fraction of that time is spent accessing properties on objects. In fact, the slowest laptops being produced today can access <em class="markup--em markup--p-em">millions of properties per second.</em></p><p name="4956" id="4956" class="graf--p"><strong class="markup--strong markup--p-strong">That’s not your app’s bottleneck</strong>. Do yourself a favor and <a href="http://www.paulirish.com/2015/advanced-performance-audits-with-devtools/" data-href="http://www.paulirish.com/2015/advanced-performance-audits-with-devtools/" class="markup--anchor markup--p-anchor" rel="nofollow">profile your app</a> to <strong class="markup--strong markup--p-strong">discover your real performance bottlenecks</strong>. I’m sure there are a million things you should fix before you spend another moment thinking about micro-optimizations.</p><p name="e51a" id="e51a" class="graf--p"><strong class="markup--strong markup--p-strong">Not convinced?</strong> For a micro-optimization to have any appreciable impact on your app, you’d have to loop over the operation <strong class="markup--strong markup--p-strong">hundreds of thousands of times</strong>, and the only differences in micro-optimization you should ever be concerned about are the ones that are <strong class="markup--strong markup--p-strong">orders of magnitude apart</strong>.</p><p name="6229" id="6229" class="graf--p"><strong class="markup--strong markup--p-strong">Rule of thumb:</strong> Profile your app and eliminate as many loading, networking, file I/O, and rendering bottlenecks as you can find. <strong class="markup--strong markup--p-strong">Then and only then should you start to think about a micro-optimization.</strong></p><p name="fb32" id="fb32" class="graf--p">Can you tell the difference between <em class="markup--em markup--p-em">.0000000001</em> seconds and <em class="markup--em markup--p-em">.000000001</em> seconds? Neither can I, but I sure can tell the difference between loading 10 small icons or loading one web font, instead!</p><p name="06a6" id="06a6" class="graf--p">If you do <strong class="markup--strong markup--p-strong">profile your app</strong> and find that object creation really is a bottleneck, the fastest way to do it is not by using <em class="markup--em markup--p-em"><code>new</code></em> and classical OO. <strong class="markup--strong markup--p-strong">The fastest way is to use object literals</strong>. You can do so in-line with a loop and add objects to an object pool to avoid thrashing from the garbage collector. If it’s worth abandoning prototypal OO over perf, it’s worth ditching the prototype chain and inheritance altogether to crank out object literals.</p><blockquote name="c3f4" id="c3f4" class="graf--blockquote">But Google said class is fast…</blockquote><p name="c9c4" id="c9c4" class="graf--p"><strong class="markup--strong markup--p-strong">WAT? </strong>Google is building a JavaScript engine. You are building an application. Obviously what they care about and what you care about should be <strong class="markup--strong markup--p-strong">very different things</strong>. Let Google handle the micro-optimizations. You worry about <strong class="markup--strong markup--p-strong">your app’s real bottlenecks</strong>. I promise, you’ll get a whole lot better ROI focusing on just about anything else.</p><p name="6bf1" id="6bf1" class="graf--p graf--empty"><br></p><h3 name="dec9" id="dec9" class="graf--h3">Is There a Big Difference in Memory Consumption Between Classical and Prototypal?</h3><blockquote name="74f0" id="74f0" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote><p name="5898" id="5898" class="graf--p">Both can use delegate prototypes to share methods between many object instances. Both can use or avoid wrapping a bunch of state into closures.</p><p name="5884" id="5884" class="graf--p">In fact, if you start with factory functions, it’s easier to switch to object pools so that you can manage memory more carefully and avoid being blocked periodically by the garbage collector. For more on why that’s awkward with constructors, see the <strong class="markup--strong markup--p-strong">WAT?</strong> note under <em class="markup--em markup--p-em">“Does <code>new</code> mean that code is using classical inheritance?”</em></p><p name="dba2" id="dba2" class="graf--p graf--last">In other words, if you want the most flexibility for memory management, use factory functions instead of constructors and classical inheritance.</p></div></div></section><section name="b654" class=" section--content"><div class="section-divider layoutSingleColumn"><hr class="section-divider"></div><div class="section-content"><div class="section-inner layoutSingleColumn"><blockquote name="e3a3" id="e3a3" class="graf--pullquote pullquote graf--startsWithDoubleQuote graf--first graf--last">“…if you want the most flexibility for memory management,<br>use factory functions…”</blockquote></div></div></section><section name="b1f4" class=" section--content"><div class="section-divider layoutSingleColumn"><hr class="section-divider"></div><div class="section-content"><div class="section-inner layoutSingleColumn"><p name="33b0" id="33b0" class="graf--p graf--empty graf--first"><br></p><h3 name="8ed9" id="8ed9" class="graf--h3">The Native APIs use Constructors. Aren’t they More Idiomatic than Factories?</h3><p name="8d10" id="8d10" class="graf--p graf--empty"><br></p><blockquote name="1d8b" id="1d8b" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote><p name="74d0" id="74d0" class="graf--p"><strong class="markup--strong markup--p-strong">Factories are extremely common in JavaScript.</strong> For instance, the most popular JavaScript library of all time, <strong class="markup--strong markup--p-strong">jQuery</strong> exposes a factory to users. John Resig has written about the choice to use a factory and prototype extension rather than a class. Basically, it boils down to the fact that he didn’t want callers to have to type <em class="markup--em markup--p-em"><code>new</code></em> every time they made a selection. What would that have looked like?</p><figure name="5c35" id="5c35" class="graf--figure graf--iframe"><div class="iframeContainer"><iframe width="700" height="250" src="/media/1efd18420d6f00481898912c65cb97a9?maxWidth=700" data-media-id="1efd18420d6f00481898912c65cb97a9" frameborder="0"></iframe></div></figure><p name="bb8c" id="bb8c" class="graf--p">What else exposes factories?</p><ul class="postList"><li name="b663" id="b663" class="graf--li"><strong class="markup--strong markup--li-strong">React</strong> <em class="markup--em markup--li-em"><code>React.createClass()</code></em> is a factory.</li><li name="49ac" id="49ac" class="graf--li"><strong class="markup--strong markup--li-strong">Angular</strong> uses classes &amp; factories, but wraps them all with a factory in the Dependency Injection container. All providers are sugar that use the <em class="markup--em markup--li-em"><code>.provider()</code></em> factory. There’s even a <code>.&lt;em class="markup--em markup--li-em"&gt;factory()</code></em> provider, and even the <em class="markup--em markup--li-em"><code>.service()</code></em> provider wraps normal constructors and exposes … you guessed it: A <strong class="markup--strong markup--li-strong">factory</strong> for DI consumers.</li><li name="ce89" id="ce89" class="graf--li"><strong class="markup--strong markup--li-strong">Ember</strong> <em class="markup--em markup--li-em"><code>Ember.Application.create();</code></em> is a factory that produces the app. Rather than creating constructors to call with <em class="markup--em markup--li-em"><code>new</code></em>, the <em class="markup--em markup--li-em"><code>.extend()</code></em> methods augment the app.</li><li name="69bc" id="69bc" class="graf--li"><strong class="markup--strong markup--li-strong">Node</strong> core services like <em class="markup--em markup--li-em"><code>http.createServer()</code></em> and <em class="markup--em markup--li-em"><code>net.createServer()</code> </em>are factory functions.</li><li name="4854" id="4854" class="graf--li"><strong class="markup--strong markup--li-strong">Express</strong> is a factory that creates an express app.</li></ul><p name="884a" id="884a" class="graf--p">As you can see, virtually all of the most popular libraries and frameworks for JavaScript make heavy use of factory functions. <strong class="markup--strong markup--p-strong">The only object instantiation pattern more common than factories in JS is the object literal.</strong></p><p name="ada9" id="ada9" class="graf--p graf--last">JavaScript built-ins started out using constructors because Brendan Eich was told to make it look like Java. JavaScript continues to use constructors for self-consistency. It would be awkward to try to change everything to factories and deprecate constructors now.</p></div></div></section><section name="9bed" class=" section--content"><div class="section-divider layoutSingleColumn"><hr class="section-divider"></div><div class="section-content"><div class="section-inner layoutSingleColumn"><blockquote name="92cc" id="92cc" class="graf--pullquote pullquote graf--first graf--last">That doesn’t mean that <strong class="markup--strong markup--pullquote-strong">your APIs</strong> have to suck.</blockquote></div></div></section><section name="8083" class=" section--content"><div class="section-divider layoutSingleColumn"><hr class="section-divider"></div><div class="section-content"><div class="section-inner layoutSingleColumn"><p name="bc05" id="bc05" class="graf--p graf--empty graf--first"><br></p><h3 name="0eeb" id="0eeb" class="graf--h3">Isn’t Classical Inheritance More Idiomatic than Prototypal Inheritance?</h3><blockquote name="9405" id="9405" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote><p name="6dd1" id="6dd1" class="graf--p">Every time I hear this misconception I am tempted to say, <strong class="markup--strong markup--p-strong">“do u even JavaScript?”</strong> and move on… but I’ll resist the urge and set the record straight, instead.</p><p name="6faf" id="6faf" class="graf--p">Don’t feel bad if this is your question, too. It’s <strong class="markup--strong markup--p-strong">not your fault</strong>. <a href="https://medium.com/javascript-scene/javascript-training-sucks-284b53666245" data-href="https://medium.com/javascript-scene/javascript-training-sucks-284b53666245" class="markup--anchor markup--p-anchor">JavaScript Training Sucks!</a></p><p name="acc0" id="acc0" class="graf--p">The answer to this question is a big, gigantic</p><h2 name="1e55" id="1e55" class="graf--h2">No… (but)</h2><p name="f63f" id="f63f" class="graf--p graf--empty"><br></p><p name="720c" id="720c" class="graf--p">Prototypes are the idiomatic inheritance paradigm in JS, and <em class="markup--em markup--p-em"><code>class</code> </em>is the marauding invasive species.</p><h4 name="0be1" id="0be1" class="graf--h4">A brief history of popular JavaScript libraries:</h4><p name="e062" id="e062" class="graf--p graf--empty"><br></p><p name="b79c" id="b79c" class="graf--p">In the beginning, everybody wrote their own libs, and open sharing wasn’t a big thing. And then <strong class="markup--strong markup--p-strong">Prototype</strong> came along. (The name is a big hint here). Prototype did its magic by extending built-in <strong class="markup--strong markup--p-strong">delegate prototypes</strong> using <strong class="markup--strong markup--p-strong">concatenative inheritance</strong>.</p><p name="caf3" id="caf3" class="graf--p">Later we all realized that modifying built-in prototypes was an anti-pattern when native alternatives and conflicting libs broke the internet. But that’s a different story.</p><p name="3e30" id="3e30" class="graf--p">Next on the JS lib popularity roller coaster was <strong class="markup--strong markup--p-strong">jQuery</strong>. jQuery’s big claim to fame was <strong class="markup--strong markup--p-strong">jQuery plugins</strong>. They worked by extending jQuery’s <strong class="markup--strong markup--p-strong">delegate prototype </strong>using <strong class="markup--strong markup--p-strong">concatenative inheritance.</strong></p><blockquote name="8ac3" id="8ac3" class="graf--pullquote pullquote">Are you starting to sense a pattern here?</blockquote><p name="affe" id="affe" class="graf--p"><strong class="markup--strong markup--p-strong">jQuery remains the most popular JavaScript library ever made. By a HUGE margin. HUGE.</strong></p><p name="44c2" id="44c2" class="graf--p">This is where things get muddled and class extension starts to sneak into the language… John Resig (author of jQuery) wrote about <em class="markup--em markup--p-em">Simple Class Inheritance in JavaScript</em>, and people started <em class="markup--em markup--p-em">actually using it,</em> even though John Resig himself didn’t think it belonged in jQuery (because <strong class="markup--strong markup--p-strong">prototypal OO did the same job better</strong>).</p><p name="717e" id="717e" class="graf--p">Semi-popular Java-esque frameworks like ExtJS appeared, ushering in the first kinda, sorta, not-really mainstream uses of class in JavaScript. This was 2007. JavaScript was <strong class="markup--strong markup--p-strong">12 years old</strong> before a somewhat popular lib started exposing JS users to classical inheritance.</p><p name="cfb5" id="cfb5" class="graf--p">Three years later, Backbone <strong class="markup--strong markup--p-strong">exploded</strong> and had an <em class="markup--em markup--p-em"><code>.extend()</code></em> method that mimicked class inheritance, including all its nastiest features such as brittle object hierarchies. That’s when <em class="markup--em markup--p-em">all hell broke loose.</em></p><blockquote name="0bd0" id="0bd0" class="graf--blockquote">~100kloc app starts using Backbone. A few months in I’m debugging a 6-level hierarchy trying to find a bug. Stepped through every line of constructor code up the <code>super</code> chain. Found and fixed the bug in the top level base class. Then had to fix a lot of child classes because they depended on the buggy behavior of the base class. <strong class="markup--strong markup--blockquote-strong">Hours of frustration</strong> that <strong class="markup--strong markup--blockquote-strong">should have been a 5 minute fix</strong>.</blockquote><p name="6f2c" id="6f2c" class="graf--p"><strong class="markup--strong markup--p-strong"><em class="markup--em markup--p-em">This is not JavaScript.</em></strong> I was suddenly living in <em class="markup--em markup--p-em">Java hell</em> again. That lonely, dark, scary place where any quick movements could cause entire hierarchies to shudder and collapse in coalescing, tight-coupled convulsions.</p><p name="fc83" id="fc83" class="graf--p"><strong class="markup--strong markup--p-strong">These are the monsters rewrites are made of.</strong></p><p name="346f" id="346f" class="graf--p">But, squirreled away in the Backbone docs, a ray of golden sunshine:</p><figure name="a3d9" id="a3d9" class="graf--figure graf--iframe"><div class="iframeContainer"><iframe width="700" height="250" src="/media/7147ee8f2990055bbee5538ffd118419?maxWidth=700" data-media-id="7147ee8f2990055bbee5538ffd118419" frameborder="0"></iframe></div></figure><p name="2b39" id="2b39" class="graf--p">Our old friend, <strong class="markup--strong markup--p-strong">concatenative inheritance</strong> saving the day with a <em class="markup--em markup--p-em"><code>Backbone.Events</code></em> <strong class="markup--strong markup--p-strong">mixin</strong>.</p><p name="e153" id="e153" class="graf--p graf--last">It turns out, if you look at <strong class="markup--strong markup--p-strong">any non-trivial JavaScript library</strong> closely enough, <strong class="markup--strong markup--p-strong">you’re going to find examples of concatenation and delegation</strong>. It’s so common and automatic for JavaScript developers to do these things that <strong class="markup--strong markup--p-strong">they don’t even think of it as inheritance</strong>, even though it <strong class="markup--strong markup--p-strong">accomplishes the same goal.</strong></p></div></div></section><section name="13a5" class=" section--content"><div class="section-divider layoutSingleColumn"><hr class="section-divider"></div><div class="section-content"><div class="section-inner layoutSingleColumn"><blockquote name="93ef" id="93ef" class="graf--pullquote pullquote graf--first">Inheritance in JS is so easy<br>it confuses people who expect it to take effort.</blockquote><blockquote name="ab9a" id="ab9a" class="graf--pullquote pullquote graf--last">To make it harder, we added <code>class</code>.</blockquote></div></div></section><section name="987f" class=" section--content"><div class="section-divider layoutSingleColumn"><hr class="section-divider"></div><div class="section-content"><div class="section-inner layoutSingleColumn"><p name="6ca2" id="6ca2" class="graf--p graf--first">And how did we add class? <strong class="markup--strong markup--p-strong">We built it on top of prototypal inheritance</strong> using <strong class="markup--strong markup--p-strong">delegate prototypes</strong> and <strong class="markup--strong markup--p-strong">object concatenation</strong>, of course!</p><p name="5c3d" id="5c3d" class="graf--p"><strong class="markup--strong markup--p-strong">That’s like driving your Tesla Model S to a car dealership and trading it in for a rusted out 1983 Ford Pinto.</strong></p><p name="c7b5" id="c7b5" class="graf--p graf--empty"><br></p><h3 name="88ab" id="88ab" class="graf--h3">Doesn’t the Choice Between Classical and Prototypal Inheritance Depend on the Use Case?</h3><blockquote name="be2b" id="be2b" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote><p name="e342" id="e342" class="graf--p">Prototypal OO is simpler, more flexible, and a lot less error prone. I have been making this claim and challenging people to come up with a compelling class use case <em class="markup--em markup--p-em">for many years. </em>Hundreds of thousands of people have heard the call. The few answers I’ve received depended on one or more of the misconceptions addressed in this article.</p><p name="d72b" id="d72b" class="graf--p">I was once a classical inheritance fan. I bought into it completely. I built object hierarchies everywhere. I built visual OO Rapid Application Development tools to help software architects design object hierarchies and relationships that made sense. It took a visual tool to truly map and graph the object relationships in enterprise applications using classical inheritance taxonomies.</p><p name="c9c9" id="c9c9" class="graf--p">Soon after my transition from C++ and Java to JavaScript, I stopped doing all of that. Not because I was building less complex apps (the opposite is true), but because JavaScript was so much simpler, I had no more need for all that OO design tooling.</p><p name="d801" id="d801" class="graf--p">I used to do application design consulting and frequently recommend sweeping rewrites. Why? Because <strong class="markup--strong markup--p-strong">all object hierarchies are eventually wrong for new use cases.</strong></p><p name="222b" id="222b" class="graf--p">I wasn’t alone. In those days, <strong class="markup--strong markup--p-strong">complete rewrites</strong> were very common for new software versions. Most of those rewrites were necessitated by legacy lock-in caused by <a href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3" data-href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3" class="markup--anchor markup--p-anchor">arthritic, brittle class hierarchies</a>. Entire books were written about OO design mistakes and how to avoid them or refactor away from them. It seemed like every developer had a copy of <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;camp=213733&amp;creative=393185&amp;creativeASIN=0201633612&amp;linkCode=shr&amp;tag=eejs-20&amp;linkId=QYF6ABRMZ4O6KML2" data-href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;camp=213733&amp;creative=393185&amp;creativeASIN=0201633612&amp;linkCode=shr&amp;tag=eejs-20&amp;linkId=QYF6ABRMZ4O6KML2" class="markup--anchor markup--p-anchor" rel="nofollow">“Design Patterns”</a> on their desk.</p><p name="46f8" id="46f8" class="graf--p">I recommend that you follow the <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;camp=213733&amp;creative=393185&amp;creativeASIN=0201633612&amp;linkCode=shr&amp;tag=eejs-20&amp;linkId=QYF6ABRMZ4O6KML2" data-href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;camp=213733&amp;creative=393185&amp;creativeASIN=0201633612&amp;linkCode=shr&amp;tag=eejs-20&amp;linkId=QYF6ABRMZ4O6KML2" class="markup--anchor markup--p-anchor" rel="nofollow">Gang of Four’s advice</a> on this point:</p><blockquote name="317c" id="317c" class="graf--pullquote pullquote graf--startsWithDoubleQuote">“Favor object composition over class inheritance.”</blockquote><p name="480a" id="480a" class="graf--p">In Java, that was harder than class inheritance because you actually had to use classes to achieve it.</p><p name="aeba" id="aeba" class="graf--p">In JavaScript, we don’t have that excuse. It’s actually <strong class="markup--strong markup--p-strong">much easier </strong>in JavaScript to simply create the object that you need by assembling various <strong class="markup--strong markup--p-strong">prototypes</strong> together than it is to manage object hierarchies.</p><p name="c987" id="c987" class="graf--p"><strong class="markup--strong markup--p-strong">WAT? </strong>Seriously. Want the jQuery object that can turn any date input into a <em class="markup--em markup--p-em"><code>megaCalendarWidget</code></em>? You don’t have to<em class="markup--em markup--p-em"><code>extend</code></em> a <em class="markup--em markup--p-em"><code>class</code></em>. JavaScript has dynamic object extension, and jQuery exposes its own prototype so you can just extend that — without an extend keyword! <strong class="markup--strong markup--p-strong">WAT?:</strong></p><figure name="aceb" id="aceb" class="graf--figure graf--iframe"><div class="iframeContainer"><iframe width="700" height="250" src="/media/d46c084f2d3ad2eb9349d367943a141f?maxWidth=700" data-media-id="d46c084f2d3ad2eb9349d367943a141f" frameborder="0"></iframe></div></figure><p name="a856" id="a856" class="graf--p">The next time you call the jQuery factory, you’ll get an instance that can make your date inputs mega awesome.</p><p name="1a02" id="1a02" class="graf--p">Similarly, you can use <em class="markup--em markup--p-em"><code>Object.assign()</code> </em>to compose any number of objects together with last-in priority:</p><figure name="2e11" id="2e11" class="graf--figure graf--iframe"><div class="iframeContainer"><iframe width="700" height="250" src="/media/105db7f26614c7111022a5ddc44cb197?maxWidth=700" data-media-id="105db7f26614c7111022a5ddc44cb197" frameborder="0"></iframe></div></figure><p name="26dd" id="26dd" class="graf--p">No, really — <strong class="markup--strong markup--p-strong">any number of objects:</strong></p><figure name="06bd" id="06bd" class="graf--figure graf--iframe"><div class="iframeContainer"><iframe width="700" height="250" src="/media/b35c15e99590b6a785cb577c609675d1?maxWidth=700" data-media-id="b35c15e99590b6a785cb577c609675d1" frameborder="0"></iframe></div></figure><p name="d949" id="d949" class="graf--p">This technique is called <strong class="markup--strong markup--p-strong">concatenative inheritance</strong>, and the prototypes you inherit from are sometimes referred to as <strong class="markup--strong markup--p-strong">exemplar prototypes</strong>, which differ from delegate prototypes in that you <strong class="markup--strong markup--p-strong">copy from them</strong>, rather than delegate to them.</p><p name="1338" id="1338" class="graf--p graf--empty"><br></p><h3 name="ed9d" id="ed9d" class="graf--h3">ES6 Has the <code>class</code> keyword. Doesn’t that mean we should all be using it?</h3><blockquote name="8a2b" id="8a2b" class="graf--pullquote pullquote"><strong class="markup--strong markup--pullquote-strong">No.</strong></blockquote><p name="3606" id="3606" class="graf--p">There are lots of <a href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3" data-href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-ee6f3281e7f3" class="markup--anchor markup--p-anchor">compelling reasons</a> to <a href="https://medium.com/javascript-scene/how-to-fix-the-es6-class-keyword-2d42bb3f4caf" data-href="https://medium.com/javascript-scene/how-to-fix-the-es6-class-keyword-2d42bb3f4caf" class="markup--anchor markup--p-anchor">avoid the ES6 <em class="markup--em markup--p-em"><code>class</code></em> keyword</a>, not least of which because it’s an awkward fit for JavaScript.</p><p name="dd38" id="dd38" class="graf--p">We already have an <strong class="markup--strong markup--p-strong">amazingly powerful and expressive object system</strong> in JavaScript. The concept of class as it’s implemented in JS today is more restrictive (in a bad way, not in a cool type-correctness way), and obscures the <a href="http://ericleads.com/2013/02/fluent-javascript-three-different-kinds-of-prototypal-oo/" data-href="http://ericleads.com/2013/02/fluent-javascript-three-different-kinds-of-prototypal-oo/" class="markup--anchor markup--p-anchor" rel="nofollow">very cool prototypal OO system</a> that was built into the language a long time ago.</p><p name="b980" id="b980" class="graf--p">You know what would really be good for JavaScript? Better sugar and abstractions built on top of prototypes <strong class="markup--strong markup--p-strong">from the perspective of a programmer familiar with prototypal OO.</strong></p><p name="d631" id="d631" class="graf--p graf--last">That could be <a href="https://github.com/ericelliott/stampit" data-href="https://github.com/ericelliott/stampit" class="markup--anchor markup--p-anchor" rel="nofollow">really cool</a>.</p>
  500. </div></p>
  501. </article>
  502. </section>
  503. <nav id="jumpto">
  504. <p>
  505. <a href="/david/blog/">Accueil du blog</a> |
  506. <a href="https://medium.com/javascript-scene/common-misconceptions-about-inheritance-in-javascript-d5d9bab29b0a">Source originale</a> |
  507. <a href="/david/stream/2019/">Accueil du flux</a>
  508. </p>
  509. </nav>
  510. <footer>
  511. <div>
  512. <img src="/static/david/david-larlet-avatar.jpg" loading="lazy" class="avatar" width="200" height="200">
  513. <p>
  514. Bonjour/Hi!
  515. Je suis <a href="/david/" title="Profil public">David&nbsp;Larlet</a>, je vis actuellement à Montréal et j’alimente cet espace depuis 15 ans. <br>
  516. Si tu as apprécié cette lecture, n’hésite pas à poursuivre ton exploration. Par exemple via les <a href="/david/blog/" title="Expériences bienveillantes">réflexions bimestrielles</a>, la <a href="/david/stream/2019/" title="Pensées (dés)articulées">veille hebdomadaire</a> ou en t’abonnant au <a href="/david/log/" title="S’abonner aux publications via RSS">flux RSS</a> (<a href="/david/blog/2019/flux-rss/" title="Tiens c’est quoi un flux RSS ?">so 2005</a>).
  517. </p>
  518. <p>
  519. Je m’intéresse à la place que je peux avoir dans ce monde. En tant qu’humain, en tant que membre d’une famille et en tant qu’associé d’une coopérative. De temps en temps, je fais aussi des <a href="https://github.com/davidbgk" title="Principalement sur Github mais aussi ailleurs">trucs techniques</a>. Et encore plus rarement, <a href="/david/talks/" title="En ce moment je laisse plutôt la place aux autres">j’en parle</a>.
  520. </p>
  521. <p>
  522. Voici quelques articles choisis :
  523. <a href="/david/blog/2019/faire-equipe/" title="Accéder à l’article complet">Faire équipe</a>,
  524. <a href="/david/blog/2018/bivouac-automnal/" title="Accéder à l’article complet">Bivouac automnal</a>,
  525. <a href="/david/blog/2018/commodite-effondrement/" title="Accéder à l’article complet">Commodité et effondrement</a>,
  526. <a href="/david/blog/2017/donnees-communs/" title="Accéder à l’article complet">Des données aux communs</a>,
  527. <a href="/david/blog/2016/accompagner-enfant/" title="Accéder à l’article complet">Accompagner un enfant</a>,
  528. <a href="/david/blog/2016/senior-developer/" title="Accéder à l’article complet">Senior developer</a>,
  529. <a href="/david/blog/2016/illusion-sociale/" title="Accéder à l’article complet">L’illusion sociale</a>,
  530. <a href="/david/blog/2016/instantane-scopyleft/" title="Accéder à l’article complet">Instantané Scopyleft</a>,
  531. <a href="/david/blog/2016/enseigner-web/" title="Accéder à l’article complet">Enseigner le Web</a>,
  532. <a href="/david/blog/2016/simplicite-defaut/" title="Accéder à l’article complet">Simplicité par défaut</a>,
  533. <a href="/david/blog/2016/minimalisme-esthetique/" title="Accéder à l’article complet">Minimalisme et esthétique</a>,
  534. <a href="/david/blog/2014/un-web-omni-present/" title="Accéder à l’article complet">Un web omni-présent</a>,
  535. <a href="/david/blog/2014/manifeste-developpeur/" title="Accéder à l’article complet">Manifeste de développeur</a>,
  536. <a href="/david/blog/2013/confort-convivialite/" title="Accéder à l’article complet">Confort et convivialité</a>,
  537. <a href="/david/blog/2013/testament-numerique/" title="Accéder à l’article complet">Testament numérique</a>,
  538. et <a href="/david/blog/" title="Accéder aux archives">bien d’autres…</a>
  539. </p>
  540. <p>
  541. On peut <a href="mailto:david%40larlet.fr" title="Envoyer un courriel">échanger par courriel</a>. Si éventuellement tu souhaites que l’on travaille ensemble, tu devrais commencer par consulter le <a href="http://larlet.com">profil dédié à mon activité professionnelle</a> et/ou contacter directement <a href="http://scopyleft.fr/">scopyleft</a>, la <abbr title="Société coopérative et participative">SCOP</abbr> dont je fais partie depuis six ans. Je recommande au préalable de lire <a href="/david/blog/2018/cout-site/" title="Attention ce qui va suivre peut vous choquer">combien coûte un site</a> et pourquoi je suis plutôt favorable à une <a href="/david/pro/devis/" title="Discutons-en !">non-demande de devis</a>.
  542. </p>
  543. <p>
  544. Je ne traque pas ta navigation mais mon
  545. <abbr title="Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33.184162340">hébergeur</abbr>
  546. conserve des logs d’accès.
  547. </p>
  548. </div>
  549. </footer>
  550. <script type="text/javascript">
  551. ;(_ => {
  552. const jumper = document.getElementById('jumper')
  553. jumper.addEventListener('click', e => {
  554. e.preventDefault()
  555. const anchor = e.target.getAttribute('href')
  556. const targetEl = document.getElementById(anchor.substring(1))
  557. targetEl.scrollIntoView({behavior: 'smooth'})
  558. })
  559. })()
  560. </script>