Bonjour à tous,
En ce moment je découvre les objets javascript définis via prototype et j'ai encore du mal à comprendre le fonctionnement exact:
Voici mon exemple :
2 questions :
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
52
53
54
55
56
57 $(function() { function log(p){ $("#log").append('<li>'+p+'</li>'); } function o() { this.arr = [0,1,2,3]; this.x = 'hello'; } o.prototype = { y: 'hi', debug: function(){ log("this = "+JSON.stringify(this)); log("y = "+this.y); log(''); this.arr.forEach(function(el){ log('el = '+el); log('this = '+this); }); } } var a = new o(); a.debug(); a.x = 'a'; a.y = 'b'; a.debug(); }); /* résultat : this = {"arr":[0,1,2,3],"x":"hello"} y = hi el = 0 this = [object Window] el = 1 this = [object Window] el = 2 this = [object Window] el = 3 this = [object Window] this = {"arr":[0,1,2,3],"x":"a","y":"b"} y = b el = 0 this = [object Window] el = 1 this = [object Window] el = 2 this = [object Window] el = 3 this = [object Window] */
1)
D'après ce que j'avais compris, les propriétés déclarées dans le constructeur sont publiques alors que celles définies via prototype sont privées.
La première ligne du log confortait ma croyance, on accède bien à x mais pas à y.
Malheureusement on voit que la ligne "a.y = 'b';" remplace bien la propriété y, et la rend en plus publique... Est-ce normal ?
2)
Pourquoi this reprends son comportement par défaut (Window) au lieu de me renvoyer mon objet dans le forEach ? Et comment accéder à mon objet à l'intérieur du forEach alors ?
Pour ceux qui veulent tester :
https://jsfiddle.net/mathspountz/rmchcue4/2/
Partager