Les objets « Proxy » et « Reflect » - javascript tome viii

Transcription

Les objets « Proxy » et « Reflect » - javascript tome viii
Les objets
« Proxy » et « Reflect »
J AVA S C R I P T (Programmation Internet) V O L . V I I I
Po u r D é b u t a n t s
J.B. Dadet DIASOLUKA Luyalu Nzoyifuanga
+243 - 851278216 - 899508675 - 991239212 - 902263541 - 813572818
Les « Proxies » constituent un aspect/fonctionnalité de la
« métaprogrammation » permettant d’intercepter et de
personnaliser des opérations effectuées sur les propriétés
d’objets.
On peut les assimiler :
1. À des « event listeners » particuliers destinés seulement
à intercepter des accès aux propriétés d’un objet ciblé
« target ».
2. À des « interrupt redirection » de l’assembleur.
La « métaprogrammation » permet de modifier et/ou
d’interagir avec le corps (ex. lecture) d’un code source
pendant son exécution.
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
Contrairement à la « programmation du niveau de base »
qui traite les données fournies en entrée, la « métaprogrammation » travaille sur son propre code selon les trois
types suivants de métaprogrammation : Introspection [Ob-
ject.entries()], Self-modification [auto modification de la
structure du programme], Intercession [redéfinition de la
sémantique de quelques opérations du langage].
Syntaxe de définition d’un objet « Proxy » :
const iProxy = new Proxy(target, handler, receiver);
iProxy = instance de Proxy à créer, qui permet d’intercepter
et de manipuler les opérations d’accès aux propriétés
(traps) de l’objet cible (target) – voir plus loin.
Proxy = objet parent ;
target = objet sur lequel on vent interagir (connaître ou accéder à une propriété…), c’est-à-dire l’objet qu’on vérifie ;
handler = objet contenant le/les trap(s) à exécuter lors
d’un accès aux propriétés de target. Les traps sont des
Les objets « Object » et « Reflect » -2/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
méthodes du handler, qui sont associées et invoquées aux
différentes sortes d’accès aux propriétés du target. Les différents traps sont :
1. « get » invoqué en cas d’accès à la propriété pour
lecture,
2. « set » invoqué en cas d’accès à la propriété pour affectation.
3. « has » invoqué par les opérations du genre « value in
object »,
4. « apply(target, thisArgument, argumentsList) » invoqué par un appel de fonction via
a. proxy(...argumentsList),
b. proxy.call(thisArgument, ...argumentsList),
c. proxy.apply(thisArgument, argumentsList).
5. « construct(target, argumentsList, newTarget) » invoqué en cas d’appel de constructeur via
a. new Proxy(…argumentsList)
receiver = détails du handler.
Voici une liste étendue de traps pour tous les objets :

defineProperty(target, propKey, propDesc) : boolean
o Object.defineProperty(proxy, propKey,
propDesc)
Les objets « Object » et « Reflect » -3/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu










JavaScript Tome-VIII
deleteProperty(target, propKey) : boolean
o delete proxy[propKey]
o delete proxy.foo // propKey = 'foo'
get(target, propKey, receiver) : any
o receiver[propKey]
o receiver.foo // propKey = 'foo'
getOwnPropertyDescriptor(target, propKey) : PropDesc|Undefined
o Object.getOwnPropertyDescriptor(proxy,
propKey)
getPrototypeOf(target) : Object|Null
o Object.getPrototypeOf(proxy)
has(target, propKey) : boolean
o propKey in proxy
isExtensible(target) : boolean
o Object.isExtensible(proxy)
ownKeys(target) : Array<PropertyKey>
o Object.getOwnPropertyPropertyNames(proxy)
o Object.getOwnPropertyPropertySymbols(proxy)
o Object.keys(proxy)
preventExtensions(target) : boolean
o Object.preventExtensions(proxy)
set(target, propKey, value, receiver) : boolean
o receiver[propKey] = value
o receiver.foo = value
setPrototypeOf(target, proto) : boolean
o Object.setPrototypeOf(proxy, proto)
<script>
const TargetedObject = {
existProp:"AnyValue"
};
const proxyHandler = {
get( TargetedObject,
TargetedObject_PropertyKey,
receiver ) {
console.log(
`*** In the proxyHandler's "get"`);
console.log(TargetedObject_PropertyKey);
console.log(receiver);
return "Proxy Returned value ***\n\n";
Les objets « Object » et « Reflect » -4/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
}
};
const iProxy =
new Proxy(TargetedObject, proxyHandler);
// Tentative d'accès à des prop du target.
console.log(iProxy.dumProp);
console.log(iProxy.existProp);
</script>
Exécution:
Avec les détails suivants des proxies:
Les objets « Object » et « Reflect » -5/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
et
Un autre exemple :
<script type="text/javascript">
const objetCibledeProxy = {a:45 , b:"bAttr"};
const handlerObj = {
get(paramTarget, ownPropKey, receiver) {
let r = paramTarget["a"] *= 3;
console.log(
'inside *Get* trap with' , ownPropKey );
return "Retour du GET ds handlerObj = " + r;
},
set(paramTarget, ownPropKey, receiver) {
let r = paramTarget[ownPropKey] += " de Demo";
console.log(
'inside *SET* trap with' , ownPropKey );
// inside *SET* trap with newProperty
return "Retour du SET ds handlerObj = " + r;
// N'a aucun effet
},
has(paramTarget, ownPropKey, receiver) {
let r =
`Propriété « ${ownPropKey} » in `+
`${paramTarget} = `+
`${ownPropKey in paramTarget}` ;
Les objets « Object » et « Reflect » -6/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
console.log(
`inside *HAS* trap with ${ownPropKey}`);
console.log(r);
return r;
// Chaîne non vide ?
}
};
// ====================
// Création d'un Proxy.
const oProxy =
new Proxy(objetCibledeProxy, handlerObj);
// ====================
// console.log("* Action SET");
// Modification de valeur d'une propriété
// de oProxy, ce qui déclenche
// l'exécution de set().
const sr =
oProxy.newProperty = "appel implicite de set";
console.log(sr);
// appel implicite de set
console.log(objetCibledeProxy["a"]=100);
// 100
console.log("* Action GET");
// * Action GET
// Accès à une propriété même inexistante
// de oProxy, ce qui déclenche
// l'exécution de get().
const r = oProxy.newProperty;
// inside *Get* trap with newProperty
console.log(r);
// Retour du GET ds handlerObj = 300
Les objets « Object » et « Reflect » -7/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
console.log(objetCibledeProxy["a"]);
// 300
console.log("* Action HAS");
// * Action HAS
// Vérification d'appartencance de propriété
// ds oProxy, ce qui déclenche l'exécution de has().
// Appel implicite de has
console.log("b" in oProxy);
// inside *HAS* trap with b
// Propriété « b » in [object Object] = true
// true
console.log("belly" in oProxy);
// inside *HAS* trap with belly
// Propriété « belly » in [object Object] = false
// true
let h;
h = Object.keys('objetCibledeProxy')[2] in oProxy;
// inside *HAS* trap with 2
// Propriété « 2 » in [object Object] = false
// true
console.log(h);
// true
h = Object.keys('objetCibledeProxy')[5] in oProxy;
// inside *HAS* trap with 5
// Propriété « 5 » in [object Object] = false
console.log(h);
// true
// Avec Reflect... c'est plus simple
// mais on ne peut pas définir soi-même
// les actions à entreprendre.
Les objets « Object » et « Reflect » -8/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
console.log(Reflect.has(objetCibledeProxy , "belly"));
// false
console.log(Reflect.has(objetCibledeProxy , "b"));
// true
Reflect.set(objetCibledeProxy, "f" , 2019);
console.log(`objetCibledeProxy["f"] = `+
`${objetCibledeProxy.f}`);
// objetCibledeProxy["f"] = 2019
console.log(Reflect.get(objetCibledeProxy, 'a'));
// 300
console.log(Reflect.get(objetCibledeProxy, 'b'));
// bAttr
console.log(Reflect.get(objetCibledeProxy, 'c'));
// undefined
console.log(Reflect.get(objetCibledeProxy, 'f'));
// 2019
// On peut aussi utiliser la méthode conventionnelle
// mais on ne peut pas définir soi-même
// les actions à entreprendre.
console.log("b" in objetCibledeProxy);
// true
console.log("belly" in objetCibledeProxy);
// false
</script>
Exécution :
Les objets « Object » et « Reflect » -9/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
Les méthodes de l’objet « Reflect » pour intercepter les
opérations sur les propriétés, très pratique si on incorpore
« Reflect » dans le handler d’un proxy :
Reflect.apply(target, thisArgument, argumentsList) : tout
eqv Function.prototype.apply().
Reflect.construct(target, argumentsList, newTarget=target) : Object
Reflect.defineProperty(target, propertyKey, propDesc) : boolean
eqv Object.defineProperty().
Reflect.deleteProperty(target, propertyKey) : boolean
Reflect.get(target, propertyKey, receiver=target) : tout
Reflect.getOwnPropertyDescriptor(target, propertyKey) :
PropDesc|Undefined
eqv Object.getOwnPropertyDescriptor().
Reflect.getPrototypeOf(target) : Object|Null
eqv Object.getPrototypeOf().
Reflect.has(target, propertyKey) : boolean
Reflect.isExtensible(target) : boolean
Les objets « Object » et « Reflect » -10/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
eqv Object.isExtensible().
JavaScript Tome-VIII
Reflect.ownKeys(target) : Array<PropKeys>
Retourne dans une Array toutes les keys des propriétés (strings et
symbols).
Reflect.preventExtensions(target) : boolean
eqv Object.preventExtensions().
Reflect.set(target, propertyKey, value, receiver=target) : boolean
Reflect.setPrototypeOf(target, proto) : boolean
Référence :
Pour une meilleure précision, clarté, détails et plus de simplicité, référez-vous à la page du géant génie en Informatique,
Dr Axel Rauschmayer :
http://exploringjs.com/es6/ch_proxies.html .
Les objets « Object » et « Reflect » -11/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
Kinshasa, le mercredi 26 juin 2019 - 6:00:42 PM
Mots-clés :
Proxy, proxies, métaprogrammation, trap, Introspection, Self-modification,
Intercession, intercepter, personnaliser, propriétés, event listeners, target,
Object, interrupt redirection
DIASOLUKA Nz. Luyalu
Docteur en Médecine, Chirurgie & Accouchements (1977),
CNOM : 0866 - Spécialiste en ophtalmologie (1980)
Études humanités : Scientifique - Mathématiques & Physique.
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 - 991239212 - 902263541 - 813572818
[email protected]
Autre Lecture :
https://www.scribd.com/document/374738470/Le-Plus-Grand-Secret-de-La-
Les objets « Object » et « Reflect » -12/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
Creation
D’autres publications pouvant aussi intéresser :
• https://www.scribd.com/document/377036251/Le-DosageDes-Medicaments-en-Cac-Cas
• https://www.scribd.com/document/377035454/Le-HasardDes-Thermometres-Non-contact-a-Infrarouge
• https://www.scribd.com/document/376222482/PetiteIntroduction-Aux-Fonctions-JavaScript
• https://www.scribd.com/document/376221919/La-Foi-enJesus-Christ-Pour-Quoi-Faire
• https://www.scribd.com/document/375689778/Lacuitevisuelle-angulaire
• https://www.scribd.com/document/375349851/La-variableThis
• https://www.scribd.com/document/375024162/FonctionsImbriquees-en-JS
• https://www.scribd.com/document/374789297/FormatInterne-Des-Objets-JavaScript
• https://www.scribd.com/document/374788758/Iterations-enJavaScript
• https://www.scribd.com/document/374738470/Le-PlusGrand-Secret-de-La-Creation
• https://www.scribd.com/document/374597969/NouvelleFormule-d-IMC-indice-de-doduite-Selon-Dr-Diasoluka
• https://www.scribd.com/document/373847209/PropertyDescriptors
• https://www.scribd.com/document/373833282/l-ObjetGlobal-Window
• https://www.scribd.com/document/372665249/JavascriptLes objets « Object » et « Reflect » -13/14- mercredi, 26. juin 2019 (6:00 )
J.D.B. DIASOLUKA Nz. Luyalu
JavaScript Tome-VIII
Tome-II
• https://www.scribd.com/document/355291488/motiliteoculaire-2
• https://www.scribd.com/document/355291239/motiliteoculaire-I
• https://www.scribd.com/document/355290248/Script-dAnalyses-Des-Reflexes-Pupillomoteurs
•
https://www.scribd.com/document/321168468/Renseignement
s-Id-et-Anthropometriques
• https://www.scribd.com/document/320856721/Emission-31Jul-2016
•
https://www.scribd.com/document/318182982/ComplicationVisuelle-du-Traitement-de-La-Malaria
• https://www.scribd.com/document/318180637/RapportEntre-Oxymetrie-Et-Type-Respiration
•
https://www.scribd.com/document/315746265/ClassificationDes-Medicaments
•
https://www.scribd.com/document/315745909/IncongruencesHeresies-et-Heterodoxies-de-la-Notion-de-Laboratoire
• https://www.scribd.com/document/315745725/RapportEntre-Oxymetrie-Et-Type-Respiration
Les objets « Object » et « Reflect » -14/14- mercredi, 26. juin 2019 (6:00 )

Documents pareils