Vous êtes sur la page 1sur 14

J.B.

Dadet DIASOLUKA Luyalu Nzoyifuanga


J AVA S C R I P T (Programmation Internet) V O L . V I
+243 - 851278216 - 899508675 - 995624714 - 902263541 - 813572818

CHAPITRE 11 : LES PROPRIÉTÉS:

On peut accéder aux propriétés d’un objet de plusieurs façons :

1 Par le nom de la propriété. entre guillemets dans des crochets


2 Par le nom de la propriété précédé d’un point
3 Par un index

<script type="text/javascript">
"use strict";
var dObj = {
couleur:"rose",
50: "Cinquante",
age:45,
[2]:function(){console.log("Hello")},
3: "Trois",
["quatre"]:function(){console.log("quatre")}
}
// var dObj = new dObj();

console.log(dObj["couleur"])
console.log(dObj["50"])
console.log(dObj.age)
dObj[2]()
console.log(dObj[3])
dObj["quatre"]()
console.log("=====")
for(var i in dObj)console.log(i+". "+dObj[i])
console.log(Object.values(dObj))
console.log(">===<")
for(i in dObj)console.log(dObj[i])
</script>

Exécution :

rose test.html:14:3
Cinquante test.html:15:3
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
45 test.html:16:3
Hello test.html:7:23
Trois test.html:18:3
quatre test.html:9:30
===== test.html:20:3
2. function(){console.log("Hello")} test.html:21:21
3. Trois test.html:21:21
50. Cinquante test.html:21:21
couleur. rose test.html:21:21
age. 45 test.html:21:21
quatre. function(){console.log("quatre")} test.html:21:21
Array [
dObj(), "Trois", "Cinquante", "rose", 45, dObj()
] test.html:22:3
>===< test.html:23:3
dObj()
length: 0
name: "2"
prototype: Object { … }
__proto__: function () test.html:24:17
Trois test.html:24:17
Cinquante test.html:24:17
rose test.html:24:17
45 test.html:24:17
dObj() test.html:24:17
length: 0
name: "quatre"
prototype: Object { … }
__proto__: function ()

Parcourir les éléments d’une collection / itération (array, object...) avec


un itérateur comme “ keys ”!

Object.keys -> function keys()


Array.prototype.keys -> function keys()

<script type="text/javascript"> "use strict";


let _arr = ['ally', 'belly', 'chore'];
let our_Aiterator = _arr.keys();
console.log(our_Aiterator); // Array Iterator { }
for (let i of our_Aiterator) {
console.log(i,_arr[i]); // 0 ally , 1 belly , 2 chore
}
let our_Aiterator2 = Object.keys(_arr);
console.log(our_Aiterator2); // Array [ "0", "1", "2" ]

Variables & Functions - 2 / 14 - vendredi, 6. juillet 2018 (10:11 )


J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
for (let i of our_Aiterator2) {
console.log(i,_arr[i]); // 0 ally , 1 belly , 2 chore
}

let _obj =
{"5":'ally', b:'belly', 3:'chore', _obj:45};

// « let _obj » et « _obj:45 == _obj._obj=45 »


// ne partagent pas le mê me Name Space et
// n'interfê rent donc pas.
console.log(_obj);
// Object { 3: "chore", 5: "ally", b: "belly", _obj: 45 }

console.log(_obj._obj); // 45

let our_Oiterator = Object.keys(_obj);


console.log(our_Oiterator);
// Array [ "3", "5", "b", "_obj" ]
for (let i of our_Oiterator) {
console.log(i,_obj[i]);
// 3 chore , 5 ally , b belly , _obj 45
}
</script>

CHAPITRE 12 : LES PROPRIÉTÉS ET LEURS ATTRIBUTS:

Les propriétés sont des objets dont les propriétés sont leurs attributs.

Sur https://www.ecma-international.org/ecma-262/8.0 nous lisons ceci :

6.1.7.1 Property Attributes


Attributes are used in this specification to define and explain the state of
Object properties. A data property associates a key value with the attrib-
utes listed in Table 2.
Table 2: Attrib- Value Domain Description
utes of a Data
Property At-
tribute Name

Variables & Functions - 3 / 14 - vendredi, 6. juillet 2018 (10:11 )


J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
[[Value]] Any The value retrieved by a get access
ECMAScript of the property.
language type
[[Writable]] Boolean If false, attempts by ECMAScript
code to change the property's [[Val-
ue]] attribute using [[Set]] will not
succeed.
[[Enumerable]] Boolean If true, the property will be enumer-
ated by a for-in enumeration (see
13.7.5). Otherwise, the property is
said to be non-enumerable.
[[Configurable]] Boolean If false, attempts to delete the prop-
erty, change the property to be an
accessor property, or change its at-
tributes (other than [[Value]], or
changing [[Writable]] to false) will
fail.

Comme dit ci-dessus, [[value]] est la valeur que vous attribuez ou at-
tendez de l’objet.

Une propriété ayant « false » comme valeur de l’attribut Enumerable


ne figurera pas dans la liste des propriété de l’objet, générée avec
for (var in object).

<script type="text/javascript"> "use strict";


// Dê finition de propriê tê lors de la crê ation
var obj = {nom:"nomEl",matr:45};

console.log(Object.getOwnPropertyDescriptors(obj));
// Object { nom: {…}, matr: {…} }
// {…}
// matr: Object { value: 45, writable: true, enumerable:
true, … }
// nom: Object { value: "nomEl", writable: true, enumer-
able: true, … }
// {…}
// matr: {…}
Variables & Functions - 4 / 14 - vendredi, 6. juillet 2018 (10:11 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
// configurable: true
// enumerable: true
// value: 45
// writable: true
// nom: {…}
// configurable: true
// enumerable: true
// value: "nomEl"
// writable: true

console.log(obj["nom"], obj.matr);
// nomEl 45

// [Re]Dê finition brê ve avec defineProperty


Object.defineProperty(obj, 'defProp', {
value: "definedProp" });
console.log(obj["nom"], obj['matr'], obj.matr,
obj.defProp);
// nomEl 45 45 definedProp

console.log(Object.getOwnPropertyDescriptor(obj,"nom"));
// Object { value: "nomEl", writable: true, enumerable:
true, configurable: true }
// {…}
// configurable: true
// enumerable: true
// value: "nomEl"
// writable: true

console.log(Object.getOwnPropertyDescriptor(
obj,"defProp"));
// Object { value: "definedProp", writable: false, enumer-
able: false, configurable: false }
// {…}
// configurable: false
// enumerable: false
// value: "definedProp"
// writable: false
</script>

Ci-dessous, voici comment on peut manipuler ces attributs :

1er Définir une propriété : avec la méthode Object.defineProperty

Object.defineProperty([objet], [property-key], { val-


ue: [property-value] })

Variables & Functions - 5 / 14 - vendredi, 6. juillet 2018 (10:11 )


J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
[] = à fournir.

2e Lire une ou les propriété(s) : .avec la méthode Ob-


ject.getOwnPropertyDescriptors.

Object.getOwnPropertyDescriptors([objet])

On peut définir les propriétés d’un objet [et éventuellement les attri-
buts de ces propriétés] de plusieurs façons ;

<script type="text/javascript"> "use strict";


// Donne aussi les valeurs par dê faut des attributs des
// propriê tê s selon les diffê rents modes de dê finition.
// Dê finition de propriê tê lors de la crê ation
var obj = {nom:"nomEl",matr:45};
// Dê finition directe de propriê tê ê partir
// du monde externe
obj['dirProp']="Direct Property";

// [Re]Dê finition brê ve avec defineProperty


Object.defineProperty(obj, 'defProp', { value: "de-
finedProp" });

// Modê le de [Re]Dê finition ê tendue avec defineProperty


// mê canisme interne.
Object.defineProperty(obj, 'defPropX', { value: "de-
finedProp Extended", configurable: true });

console.dir("obj.nom=",obj.nom); // obj.nom= nomEl


console.dir("obj.matr=",obj.matr); // obj.matr= 45

console.dir("obj.dirProp=",obj.dirProp);
// obj.dirProp= Direct Property

// Au lieu des points on peut aussi utiliser


// des crochets.
console.dir("obj['defProp']=",obj.defProp);
// obj['defProp']= definedProp
console.dir("obj.defPropX=",obj.defPropX);
// obj.defPropX= definedProp Extended

////////////////////////////
///// Dê BUT GETTER et SETTER
////////////////////////////

Variables & Functions - 6 / 14 - vendredi, 6. juillet 2018 (10:11 )


J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI

// On peut aussi utiliser des getters et setters.


// EXEMPLE DE SETTER :
Object.defineProperty(obj, "prod", {
// "get" et "set" deviendront propriê tê s
// de la propriê tê "prod" de l'objet "obj".
get: function() {
let alias1 = this.nom;
let alias2 = this.matr;
return "obj.nom= "+alias1 + " , " +
"obj.matr="+alias2;
},
set: function(details) {
var detail = details.split(" ");
this.nom = detail[0];
this.matr = detail[1];
}
})

// Accê s ordinaire
console.dir("obj=",obj);
// obj=
// Object { nom: "nomEl", matr: 45, dirProp: "Direct
Property", … }
// {…}
// defProp: "definedProp"
// defPropA: "Affectation ordinaire, toujours pos-
sible!"
// defPropX: "definedProp Extended"
// dirProp: "Direct Property"
// matr: "2018"
// nom: "JavaScript"
// prod: Getter & Setter
// <get>: function get()
// <set>: function set()
// Accê s par GETTER
console.dir("OBJ.PROD = : ",obj.prod);
// OBJ.PROD = : obj.nom= nomEl , obj.matr=45

// Appel de SETTER dê clenchê par l'affectation


// au SETTER "prod" de l'objet "obj", ce qui
// modifiera ici propriê tê s "nom" et "matr" de "obj"

obj.prod = "JavaScript 2018"


// nom deviendra "JavaScript"
// matr deviendra 2018
//////////////////////////
///// FIN GETTER et SETTER
//////////////////////////

Variables & Functions - 7 / 14 - vendredi, 6. juillet 2018 (10:11 )


J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI

obj.defPropA = "Affectation ordinaire, toujours pos-


sible!";
console.log(obj);
// Object { nom: "JavaScript", matr: "2018", dirProp: "Di-
rect Property", defPropA: "Affectation ordinaire, toujours
possible!", … }
// {…}
// defProp: "definedProp"
// defPropX: "Affectation ordinaire, toujours possible!"
// defPropX: "definedProp Extended"
// dirProp: "Direct Property"
// matr: "2018"
// nom: "JavaScript"
// prod: Getter & Setter
// <get>: function get()
// <set>: function set()
console.log(Object.getOwnPropertyDescriptors(obj))
// Object { nom: {…}, matr: {…}, dirProp: {…}, defProp:
{…}, defPropX: {…}, prod: {…}, defPropA: {…} }
// {…}
// defProp: Object { value: "definedProp", writable:
false, enumerable: false, … }
// defPropA: Object { value: "Affectation ordinaire,
toujours possible!", writable: true, enumerable: true, … }
// defPropX: Object { value: "definedProp Extended",
writable: false, enumerable: false, … }
// dirProp: Object { value: "Direct Property", writable:
true, enumerable: true, … }
// matr: Object { value: "2018", writable: true, enumer-
able: true, … }
// nom: Object { value: "JavaScript", writable: true,
enumerable: true, … }
// prod: Object { get: get(), enumerable: false, config-
urable: false, … }

/*
defProp: {…}
configurable: false
enumerable: false
value: "definedProp"
writable: false

defPropA: {…}
configurable: true
enumerable: true
value: "Affectation ordinaire, toujours possible!"
writable: true

defPropX: {…}
Variables & Functions - 8 / 14 - vendredi, 6. juillet 2018 (10:11 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
configurable: true
enumerable: false
value: "definedProp Extended"
writable: false

dirProp: {…}
configurable: true
enumerable: true
value: "Direct Property"
writable: true
matr: {…}
configurable: true
enumerable: true
value: 2018
writable: true
nom: {…}
configurable: true
enumerable: true
value: "JavaScript"
writable: true
prod: {…}
configurable: false
enumerable: false
get: function get()
set: function set()
*/
</script>

On peut aussi définir un getter et un setter directement dans le corps


de l’objet lors de la définition de cet objet :

<script type="text/javascript"> "use strict";


// Notez avec les virgules, que "get" et "set"
// sont propriê tê s de "obj".

var obj = {
libelle: 'Nom Produit',
prix: 2018,

get detailsProd() {
return {nomProd:this.libelle, prixProd:this.prix};
},

set detailsProd(name) {
var parts = name.split(" ");
this.libelle = parts[0];
Variables & Functions - 9 / 14 - vendredi, 6. juillet 2018 (10:11 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
this.prix = parts[1];
}
};

console.log("obj=",obj);
// obj=
// Object { libelle: "Nom Produit", prix: 2018, details-
Prod: Getter & Setter }
// {…}
// detailsProd: Getter & Setter
// libelle: "ECMASCRIPT_2018"
// prix: "3USD"

console.log("obj.libelle=",obj.libelle);
// obj.libelle= Nom Produit

console.log("obj.prix=",obj.prix);
// obj.prix= 2018

// AFFECTER ou MODIFIER via le SETTER


console.log(obj.detailsProd = 'ECMASCRIPT_2018 10 USD');
// ECMASCRIPT_2018 10 USD
console.log("obj.libelle=",obj.libelle);
// obj.libelle= ECMASCRIPT_2018
console.log("obj.prix=",obj.prix);
// obj.prix= 10
console.log(obj.prix = "3USD");
// 3USD
console.log("obj.detailsProd=",obj.detailsProd);
// obj.detailsProd=
// Object { nomProd: "ECMASCRIPT_2018", prixProd:
"3USD" }
// {…}
// nomProd: "ECMASCRIPT_2018"
// prixProd: "3USD"

// AVEC YANDEX
//test.html:21 obj= {libelle: "Nom Produit", prix: 2018}
// detailsProd: (...)
// libelle: "ECMASCRIPT_2018"
// prix: "3USD"
// get detailsProd: ƒ detailsProd ()
// set detailsProd: ƒ detailsProd (name)
// __proto__: Object
//test.html:29 obj.libelle= Nom Produit
//test.html:32 obj.prix= 2018

Variables & Functions - 10 / 14 - vendredi, 6. juillet 2018 (10:11 )


J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
//test.html:35 ECMASCRIPT_2018 10 USD
//test.html:38 obj.libelle= ECMASCRIPT_2018
//test.html:41 obj.prix= 10
//test.html:44 3USD
//test.html:47 obj.detailsProd = {nomProd:
"ECMASCRIPT_2018", prixProd: "3USD"}

/* obj.detailsProd =
1er {nomProd: "ECMASCRIPT_2018", prixProd: "3USD"}
A nomProd:"ECMASCRIPT_2018"
B prixProd:"3USD"
C __proto__:Object
1er detailsProd:(...)
2e libelle:"ECMASCRIPT_2018"
3e prix:"3USD"
4e get detailsProd:ƒ detailsProd()
5th set detailsProd:ƒ detailsProd(name)

6e get detailsProd:ƒ detailsProd()


A arguments:(...)
B caller:(...)
C length:0
D name:"get detailsProd"
E __proto__:ƒ ()
F [[FunctionLocation]]:test.html:9
G [[Scopes]]:Scopes[1]
I 0:Global {type: "global", name: "", object: Wi
ndow}
1st set detailsProd:ƒ detailsProd(name)
A arguments:(...)
B caller:(...)
C length:1
D name:"set detailsProd"
E __proto__:ƒ ()
F [[FunctionLocation]]:test.html:13
G [[Scopes]]:Scopes[1]
I 0:Global {type: "global", name: "", object: Wi
ndow}
1er __proto__:Object
*/
</script>

« get » et « set » définissent deux fonctions « accessor » pour la pro-


priété « detailsProd ».
Variables & Functions - 11 / 14 - vendredi, 6. juillet 2018 (10:11 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI

1er Un getter ( « get detailsProd() » ) pour accéder à la valeur de la


propriété,

et

2e Un setter ( « set detailsProd(name) » pour affecter / modifier la va-


leur de la propriété)

N.B. : Les propriété ne peuvent avoir que soit des valeurs, soit des ac-
cesseurs (set et get) , jamais les deux à la fois.

Vous avez remarqué ci-dessus que le prix introduit était « 10 USD »,


mais que le USD n’a pas été retenu. Si vous voulez que le setter ac-
cepte des entrées avec des espaces, il suffit de changer le séparateur
« name.split(' ') » en « name.split(',') » et séparer deux entrées par une
virgule.

<script type="text/javascript"> "use strict";


// Notez avec les virgules, que "get" et "set"
// sont propriê tê s de "obj".
var obj = {
libelle: 'Nom Produit',
prix: 2018,

get detailsProd() {
return {nomProd:this.libelle, prixProd:this.prix};
},

set detailsProd(name) {
var parts = name.split(",");
this.libelle = parts[0];
this.prix = parts[1];
}
};

// AFFECTER ou MODIFIER
console.log(obj.detailsProd = 'ECMASCRIPT 2018 ES 8, 10
USD AMê RICAINS');
// ECMASCRIPT 2018 ES 8, 10 USD AMê RICAINS

console.log("obj.libelle=",obj.libelle);
Variables & Functions - 12 / 14 - vendredi, 6. juillet 2018 (10:11 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI
// obj.libelle= ECMASCRIPT 2018 ES 8

console.log("obj.prix=",obj.prix);
// obj.prix= 10 USD AMê RICAINS

console.log("obj.detailsProd=",obj.detailsProd);
// obj.detailsProd=
// obj.detailsProd=
// Object { nomProd: "ECMASCRIPT 2018 ES 8", prixProd: "
10 USD AMê RICAINS" }
// {…}
// nomProd: "ECMASCRIPT 2018 ES 8"
// prixProd: " 10 USD AMê RICAINS"
</script>

vendredi, 6. juillet 2018 (10:11 ).

Variables & Functions - 13 / 14 - vendredi, 6. juillet 2018 (10:11 )


J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VI

DIASOLUKA Nz. Luyalu


Docteur en Médecine, Chirurgie & Accouchements (1977),
CNOM : 0866 - Spécialiste en ophtalmologie (1980)
Informaticien-amateur, Programmeur et WebMaster.

Chercheur indépendant, autonome et autofinancé, bénévole,


sans aucun conflit d’intérêt ou contrainte promotionnelle avec
qui qu’il soit ou quelqu’organisme ou institution / organisation
que ce soit, étatique, paraétatique ou privé, industriel ou
commercial en relation avec le sujet présenté.

+243 - 851278216 - 899508675 - 995624714 - 902263541 - 813572818

diasfb@mail2world.com

Variables & Functions - 14 / 14 - vendredi, 6. juillet 2018 (10:11 )

Vous aimerez peut-être aussi