L'attribut prototype n'est pas la propriété prototype même si les deux ne sont pas toujours distinctement présentés dans les livres/tutoriels javascript.
Ou en tout cas que je n'étais pas assez malin pour capter la nuance au premier coup d'oeil.
Du coup forcément je me demandais pourquoi ce coup tordu avec les constructeurs si on veut simplement que le prototype de x soit y, pourquoi ne pas simplement faire x.prototype = y ??
Bon, le franc est tombé, la lumière fût, et les bouquins javascript avancés deviennent de douces mélodies.
Ce post parce que pour asseoir la compréhension j'ai fait un petit code qui illustre bien (je trouve) le propos et que je pense (naïvement?) qu'il peut en aider d'autres:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 <!DOCTYPE html> <head> <SCRIPT> "use strict"; function startup(){ var theConstructor = function() {}; var parent = {toString: function() {return "parent";}}; theConstructor.prototype = parent; var falseChild = {}; falseChild.prototype = parent; var trueChild = new theConstructor(); document.getElementById("display").innerHTML = "Object.getPrototypeOf(falseChild).toString() : " + Object.getPrototypeOf(falseChild).toString() + "<p>" + "falseChild.prototype.toString() : " + falseChild.prototype.toString() + "<p>" + "falseChild.toString() : " + falseChild.toString() + "<p>" + "Object.getPrototypeOf(trueChild).toString() : " + Object.getPrototypeOf(trueChild).toString() + "<p>" + "trueChild.prototype.toString() : " + (trueChild.prototype && trueChild.prototype.toString()) + "<p>" + "trueChild.toString() : " + trueChild.toString() + "<p>" + "Object.getPrototypeOf(theConstructor).toString() : " + Object.getPrototypeOf(theConstructor).toString() + "<p>" + "theConstructor.prototype.toString() : " + theConstructor.prototype.toString() + "<p>" + "theConstructor.toString() : " + theConstructor.toString() + "<p>" + ""; } </script> </head> <body onload="startup()"> <div id="display"> </div> </body> </html>
Partager