Propriétés d’objets et leurs attributs - javascript tome xvi

publicité
LES PROPRIÉTÉS D’OBJETS ET LEURS ATTRIBUTS
J AVA S C R I P T (Programmation Internet) V O L . V I
Po u r D é b u t e r
J.B. Dadet DIASOLUKA Luyalu Nzoyifuanga
+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
2
3
Par le nom de la propriété. entre guillemets dans des crochets
Par le nom de la propriété précédé d’un point
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>
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
Exécution :
rose
test.html:14:3
Cinquante
test.html:15:3
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()
JDB DIASOLUKA Nz. Luyalu -2/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
<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" ]
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>
Ajouter des propriétés à un objet existant :
<script model="text/javascript"> "use strict";
let o = {
zumela:"Yende",
mbula:2019
}
JDB DIASOLUKA Nz. Luyalu -3/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
o.sika1 = "Mosusu";
o["sika2"]="Mombamba";
console.log(o);
</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 attributes listed in Table 2.
Table 2: Attributes of a Data
Property Attribute Name
[[Value]]
Value Domain
Description
Any
The value retrieved by a get access of
ECMAScript the property.
language
type
JDB DIASOLUKA Nz. Luyalu -4/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
Boolean
Peut-être modifié [directement].
If false, attempts by ECMAScript code
to change the property's [[Value]] attribute using [[Set]] will not succeed.
[[Enumerable]] Boolean
Invisible dans certains contextes.
If true, the property will be enumerated
by a for-in enumeration (see 13.7.5).
Otherwise, the property is said to be
non-enumerable.
[[Configurable]] Boolean
Peut être supprimée, ou
Son « property descriptor » changé.
If false, attempts to delete the property,
change the property to be an accessor
property, or change its attributes (other
than [[Value]], or changing [[Writable]]
to false) will fail.
[[Writable]]
Comme dit ci-dessus, [[value]] est la valeur que vous attribuez ou attendez de l’objet.
Une propriété ayant « false » comme valeur de l’attribut Enumerable
ne figurera pas dans la liste des propriétés 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, enumerable: true, … }
// {…}
// matr: {…}
//
configurable: true
JDB DIASOLUKA Nz. Luyalu -5/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
//
//
//
//
//
//
//
//
JavaScript Tome-VI
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, enumerable: false, configurable: false }
// {…}
//
configurable: false
//
enumerable: false
//
value: "definedProp"
//
writable: false
</script>
JDB DIASOLUKA Nz. Luyalu -6/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
Ci-dessous, voici comment on peut manipuler ces attributs :
1. Définir une propriété : avec la méthode Object.defineProperty
<script type="text/javascript"> "use strict";
Object.defineProperty(
[objet]
, [property-key]
, { value: [property-value] }
)
</script>
[] = à fournir.
2. Lire une ou les propriété(s) : .avec la méthode Object.getOwnPropertyDescriptors.
<script type="text/javascript"> "use strict";
Object.getOwnPropertyDescriptors (
[objet]
)
</script>
On peut définir les propriétés d’un objet [et éventuellement les attributs 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
JDB DIASOLUKA Nz. Luyalu -7/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
Object.defineProperty(obj, 'defProp', { value: "definedProp" });
// Modèle de [Re]Définition étendue avec defineProperty
// mécanisme interne.
Object.defineProperty(obj, 'defPropX', { value: "definedProp 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
////////////////////////////
// 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);
JDB DIASOLUKA Nz. Luyalu -8/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
// obj=
//
Object { nom: "nomEl", matr: 45, dirProp: "Direct
Property", … }
//
{…}
//
defProp: "definedProp"
//
defPropA: "Affectation ordinaire, toujours possible!"
//
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
//////////////////////////
obj.defPropA = "Affectation ordinaire, toujours possible!";
console.log(obj);
// Object { nom: "JavaScript", matr: "2018", dirProp: "Direct 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()
JDB DIASOLUKA Nz. Luyalu -9/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
//
JavaScript Tome-VI
<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, enumerable: true, … }
//
nom: Object { value: "JavaScript", writable: true,
enumerable: true, … }
//
prod: Object { get: get(), enumerable: false, configurable: false, … }
/*
defProp: {…}
configurable: false
enumerable: false
value: "definedProp"
writable: false
defPropA: {…}
configurable: true
enumerable: true
value: "Affectation ordinaire, toujours possible!"
writable: true
defPropX: {…}
configurable: true
enumerable: false
value: "definedProp Extended"
writable: false
dirProp: {…}
configurable: true
enumerable: true
value: "Direct Property"
writable: true
JDB DIASOLUKA Nz. Luyalu -10/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
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 :
JDB DIASOLUKA Nz. Luyalu -11/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
<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];
}
};
console.log("obj=",obj);
// obj=
// Object { libelle: "Nom Produit", prix: 2018, detailsProd: 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");
JDB DIASOLUKA Nz. Luyalu -12/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
// 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
//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:(...)
JDB DIASOLUKA Nz. Luyalu -13/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
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 propriété « detailsProd ».
1. Un getter ( « get detailsProd() » ) pour accéder à la valeur de la
propriété,
et
2. Un setter ( « set detailsProd(name) » pour affecter / modifier la valeur de la propriété)
N.B. : Les propriété ne peuvent avoir que soit des valeurs, soit des accesseurs (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 accepte
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
JDB DIASOLUKA Nz. Luyalu -14/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
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);
// 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>
JDB DIASOLUKA Nz. Luyalu -15/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
vendredi, 31. mai 2019 (7:32 ).
Mots-clés :
Accéder, propriétés, propriétés d’un objet, collection, itération, itérateur, keys, attributs, Object.getOwnPropertyDescriptors, getter, setter,
accesseur, get, set.
JDB DIASOLUKA Nz. Luyalu -16/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
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 liens d'intérêts 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
[email protected]
Autre Lecture :
https://www.scribd.com/document/374738470/Le-Plus-Grand-Secret-de-LaCreation
D’autres publications pouvant aussi intéresser :
• https://www.scribd.com/document/377036251/Le-Dosage-DesMedicaments-en-Cac-Cas
• https://www.scribd.com/document/377035454/Le-Hasard-DesJDB DIASOLUKA Nz. Luyalu -17/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
Thermometres-Non-contact-a-Infrarouge
• https://www.scribd.com/document/376222482/Petite-IntroductionAux-Fonctions-JavaScript
• https://www.scribd.com/document/376221919/La-Foi-en-Jesus-ChristPour-Quoi-Faire
• https://www.scribd.com/document/375689778/Lacuite-visuelleangulaire
• https://www.scribd.com/document/375349851/La-variable-This
• https://www.scribd.com/document/375024162/Fonctions-Imbriqueesen-JS
• https://www.scribd.com/document/374789297/Format-Interne-DesObjets-JavaScript
• https://www.scribd.com/document/374788758/Iterations-en-JavaScript
• https://www.scribd.com/document/374738470/Le-Plus-Grand-Secretde-La-Creation
• https://www.scribd.com/document/374597969/Nouvelle-Formule-dIMC-indice-de-doduite-Selon-Dr-Diasoluka
• https://www.scribd.com/document/373847209/Property-Descriptors
• https://www.scribd.com/document/373833282/l-Objet-Global-Window
• https://www.scribd.com/document/372665249/Javascript-Tome-II
• https://www.scribd.com/document/355291488/motilite-oculaire-2
• https://www.scribd.com/document/355291239/motilite-oculaire-I
• https://www.scribd.com/document/355290248/Script-d-Analyses-DesReflexes-Pupillomoteurs
• https://www.scribd.com/document/321168468/Renseignements-Id-etAnthropometriques
• https://www.scribd.com/document/320856721/Emission-31-Jul-2016
• https://www.scribd.com/document/318182982/Complication-Visuelledu-Traitement-de-La-Malaria
• https://www.scribd.com/document/318180637/Rapport-EntreOxymetrie-Et-Type-Respiration
• https://www.scribd.com/document/315746265/Classification-DesMedicaments
• https://www.scribd.com/document/315745909/IncongruencesHeresies-et-Heterodoxies-de-la-Notion-de-Laboratoire
• https://www.scribd.com/document/315745725/Rapport-EntreOxymetrie-Et-Type-Respiration
JDB DIASOLUKA Nz. Luyalu -18/19- vendredi, 31. mai 2019 (7:32 )
PROPRIÉTÉS & ATTRIBUTS D’OBJETS
JavaScript Tome-VI
JDB DIASOLUKA Nz. Luyalu -19/19- vendredi, 31. mai 2019 (7:32 )
Téléchargement