javascript tome viii - Le Type Primitif « Symbol() »
Transcription
javascript tome viii - Le Type Primitif « Symbol() »
J AVA S C R I P T (Programmation Internet) V O L . V I I I Po u r D é bu t an t s J.B. Dadet DIASOLUKA Luyalu Nzoyifuanga +243 - 851278216 - 899508675 - 991239212 - 902263541 - 813572818 CHAPITRE 14 : Le type primitif « Symbol () » Une propriété (plutôt « type primitif ») particulière : Symbol(). Les « Symbol » sont de « type primitif » que des objets : 1. Ils ne peuvent pas être « prototype » d’objet. 2. Les « Symbol » ne sont pas « constructeur » : on ne peut pas utiliser la syntaxe « new Symbol() »". 3. Ils ne peuvent pas générer d’instances. 4. Ils ne peuvent pas être examinés avec instanceof,… 5. Ils ne peuvent pas être dénombrés avec la boucle « for... in … » car non énumérables. 6. Ils n’apparaissent pas dans le tableau des résultats de « Object.getOwnPropertyNames() » car la propriété créée est anonyme. Voici ce que dit « ECMA-262, 9th edition, June 2018 - ECMAScript® 2018 - Language Specication » sur le type « Symbol » : 6.1.5 The Symbol Type The Symbol type is the set of all non-String values that may be used as the key of an Object property (6.1.7). Each possible Symbol value is unique and immutable. J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Each Symbol value immutably holds an associated value called [[Description]] that is either undefined or a String value. 6.1.5.1 Well-Known Symbols Well-known symbols are built-in Symbol values that are explicitly referenced by algorithms of this specification. They are typically used as the keys of properties whose values serve as extension points of a specification algorithm. Unless otherwise specified, well-known symbols values are shared by all realms (8.2). Within this specification a well-known symbol is referred to by using a notation of the form @@name, where “name” is one of the values listed in Table 1. Table 1: Well-known Symbols @@Specification Name: [[Description]] * Value and Purpose @@asyncIterator [[Symbol.asyncIterator]] * A method that returns the default AsyncIterator for an object. Called by the semantic of the for-await-of statement. @@hasInstance Le type primitif Symbol() -2/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII [[Symbol.hasInstance]] * A method that determines if a constructor object recognizes object as one of the constructor's instances. Called by the semantics of the instanceof operator. @@isConcatSpreadable [[Symbol.isConcatSpreadable]] * A Boolean valued property that if true indicates that an object should be flattened to its array elements by Array.prototype.concat method. @@iterator [[Symbol.iterator]] * A method that returns the default Iterator for an object. Called by the semantics of the for-of statement. @@match [[Symbol.match]] * A regular expression method that matches the regular expression against a string. Called by the String.prototype.match method. @@replace [[Symbol.replace]] * A regular expression method that replaces matched substrings of a string. Called by the String.prototype.replace method. @@search [[Symbol.search]] * A regular expression method that returns the index within string that matches the regular expression. Le type primitif Symbol() -3/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Called by the String.prototype.search method. @@species [[Symbol.species]] * A function valued property th is the constructor function that is used to create derived object. @@split [[Symbol.split]] * A regular expression method that splits a string at the indicates that match the regular expression. Called by the String.prototype.split method. @@toPrimitive [[Symbol.toPrimitive]] * A method that converts an object to a corresponding primitive value. Called by the ToPrimitive abstract operation. @@toStringTag [[Symbol.toStringTag]] * A String valued property that used in the creation of the default string description of a object. Accessed by the built-in method Object.prototype.toString. @@unscopables [[Symbol.unscopables]] * An object valued property whose own and inherited property names are property names that are excluded from the with environment binding of the associated object. Un petit comparatif de « Symbol » avec « String »: Le type primitif Symbol() -4/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII <script type="text/javascript"> let mySymb = Symbol("mySymb"); let ordStr = ("myStr"); console.log(mySymb); // Symbol(mySymb) console.log([mySymb]); // Array [ Symbol(mySymb) ] console.log(ordStr); // myStr console.log([ordStr]); // Array [ "myStr" ] console.log(String(mySymb)); // Symbol(mySymb) console.log(String([mySymb])); // TypeError: can't convert symbol to string // // Uncaught TypeError: Cannot convert a Symbol value to a string // at Array.join (<anonymous>) // at Array.toString (<anonymous>) // at String (<anonymous>) console.log([String(mySymb)]); // Array [ "Symbol(mySymb)" ] console.log(String(ordStr)); // myStr console.log(String([ordStr])); // myStr console.log([String(ordStr)]); // Array [ "myStr" ] console.log(ordStr.length); // 5 console.log([ordStr].length); Le type primitif Symbol() -5/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII // 1 console.log(Object.keys(mySymb)); // Array [] console.log(Object.keys(ordStr)); // Array(5) [ "0", "1", "2", "3", "4" ] console.log(Object.values(mySymb)); // Array [] console.log(Object.values(ordStr)); // Array(5) [ "m", "y", "S", "t", "r" ] console.log(Object.getOwnPropertyDescriptors(mySymb)); // Object { } // __proto__: Object console.log(Object.getOwnPropertyDescriptors(ordStr)); /* {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}, length: {…}} 0: {value: "m", writable: false, enumerable: true, configurable: false} 1: {value: "y", writable: false, enumerable: true, configurable: false} 2: {value: "S", writable: false, enumerable: true, configurable: false} 3: {value: "t", writable: false, enumerable: true, configurable: false} 4: {value: "r", writable: false, enumerable: true, configurable: false} length: {value: 5, writable: false, enumerable: false, configurable: false} __proto__: Object */ console.log(Object.getOwnPropertyNames(mySymb)); // Array [] console.log(Object.getOwnPropertyNames(ordStr)); // (6) ["0", "1", "2", "3", "4", "length"] console.log(Object.getOwnPropertySymbols(mySymb)); // Array [] Le type primitif Symbol() -6/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII console.log(Object.getOwnPropertySymbols(ordStr)); // Array [] </script> « Symbol » permet de créer des noms de variables spéciales (plutôt nom unique de clé de propriétés) uniques ayant des valeurs littérales qu’on peut utiliser comme ID (la valeur stockée dans le Symbole est utilisée comme ID), et ces valeurs des Symboles ne peuvent pas se conflictuer avec des noms de IDs préexistants/prédéfinis surtout en temps d’exécution (prévient les erreurs de temps d’exécution). En fait c’est la valeur de symbole qui est utilisée comme ID et non l’ID du symbole. Cela permet de ne pas écraser des variables ou propriétés préexistantes même quand on utilise leurs IDs. Avec les symboles on a donc deux « valeurs » : celle de la propriété, accessible via l’ID (clé) de celle-ci et qui est la valeur du Symbole qui lui aussi a son ID. La valeur du symbole est donc l’ID de la propriété. Bref, il faut considérer les symboles comme « noms d’ID unique générés automatiquement ». « Symbol » est l’équivalent de « atome » dans d’autres langages de programmation. La description d’un symbole est facultative, utile uniquement à des fins de débogage. <script type="text/javascript"> "use strict"; let o = { prop1 : "propriété prédéfinie" // Prédéfinie par qq'1 d'autre; }; console.log(o.prop1); // propriété prédéfinie // Notez le point. o.prop1="modifiée par mégarde"; console.log(o.prop1); // modifiée par mégarde // Notez le point. Le type primitif Symbol() -7/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII // Solution = Symbole. let prop1= Symbol("Descripteur"); o[prop1] = "Même ID Sans conflit"; // Notez les brackets. let prop2= Symbol.for("2e Symbole"); // idem que « Symbol("2e Symbole"); », mais le // crée sl* si le symbole n'existe pas encore. o[prop2] = "On peut créer autant de symboles !"; let prop3= Symbol(2019); o[prop3] = "Description numérique !"; console.log(o.prop1); // modifiée par mégarde // Notez le point. console.log(o[prop1]); // Même ID Sans conflit // Notez les brackets. console.log(o[prop2]); // Notez aussi les brackets. console.log(Symbol.keyFor(prop2)); // 2e Symbole console.log(Symbol.keyFor(prop1)); // undefined console.log(Object.getOwnPropertySymbols(o)); // Array(3) [ Symbol(Descripteur), Symbol(2e Symbole), Symbol(2019) ] // (3) […] // 0: Symbol(Descripteur) // 1: Symbol(2e Symbole) // 2: Symbol(2019) // length: 3 // <prototype>: Array [] </script> Le drawback de cela est de rendre les propriétés d'objets anonymes. Le type primitif Symbol() -8/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Les valeurs des symboles sont stockées dans un registre appelé « table globale de symboles ». Exemple de génération de nom unique de clé de propriété : 1. « Symbol » comme propriété : <script type="text/javascript"> const KEY1 = Symbol(); const KEY2 = Symbol(); const KEY3 = Symbol(); const KEY4 = Symbol(); const obj = { KEY3:new Date().toLocaleDateString(), [KEY4]:new Date().toLocaleTimeString() }; console.log(obj[KEY4]); // 12:07:57 console.log(obj.KEY3); // 07/03/2019 /**/ obj[KEY1] = 123; console.log(obj[KEY1]); // 123 obj.KEY2 = "abc"; console.log(obj.KEY2); // abc </script> 2. « Symbol » comme méthode : <script type="text/javascript"> const FOO = Symbol(); const obj = { [FOO](p) { // Notez les brakets return Math.log(p); } }; console.log( Le type primitif Symbol() -9/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII obj[FOO](new Date().getFullYear()) ); // 7.610357618312838 </script> 3. « Symbol » comme « get » et comme « set » : <script type="text/javascript"> this. v; const FOOs = Symbol(); let FOOg = Symbol(); const obj = { set [FOOs](p) { // Avec ou sans brakets console.log("Dans set" , FOOs, p); this.v = p; }, get FOOg() { // Avec ou sans brakets console.log("Dans get", FOOg, this.v); return "Date = "+this.v; } }; obj[FOOs] = new Date(); // Format ds description console.log(obj.FOOg); // Format ds description obj.FOOg; // Même format que dans la description </script> Ils sont générés par une « factory function » qui crée automatiquement un nouveau et unique symbole. L’unique paramètre -optionnel- sert à décrire le nom-unique de variable. <script type="text/javascript"> const varSymbol = Symbol('varSymbol'); console.log(varSymbol); // Symbol(varSymbol) console.log(varSymbol.toString() , String(varSymbol)); // Symbol(varSymbol) Symbol(varSymbol) console.log(Symbol(),Symbol()); Le type primitif Symbol() -10/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII // Symbol() Symbol() console.log(Symbol().toString(), String(Symbol())); // Symbol() Symbol() console.log(Symbol('Red'),Symbol('Red')); // Symbol(Red) Symbol(Red) console.log(Symbol('Red').toString(), String(Symbol('Red'))); // Symbol(Red) Symbol(Red) console.log(Symbol()===Symbol()); // false console.log(Symbol()==Symbol()); // false console.log(Symbol('Green')===Symbol('Green')); // false console.log(Symbol('Blue')==Symbol('Blue')); // false const vSYMBOL1 = Symbol('DESCRIPTION'); const vSYMBOL2 = Symbol('DESCRIPTION'); console.log(vSYMBOL1,vSYMBOL2); // Symbol(DESCRIPTION) Symbol(DESCRIPTION) const v="DESCRIPTION"; const vSYMBOL3 = Symbol(v); const vSYMBOL4 = Symbol(v); console.log(vSYMBOL3,vSYMBOL4); // Symbol(DESCRIPTION) Symbol(DESCRIPTION) console.log(typeof Symbol); // function console.log(typeof Symbol()); // symbol console.log(Symbol('Yellow')=Symbol('Yellow')); // YANDEX : test.html:50 // Uncaught ReferenceError: // Invalid left-hand side in assignment // at test.html:50 // Le type primitif Symbol() -11/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII // FIRFOX : // ReferenceError: // invalid assignment left-hand side test.html:50:17 </script> Exécution : Les « Symbol » ne sont pas itérables, donc ne sont pas affichés par les méthodes « Object.keys() », « Object.getOwnPropertyNames() », ni par la boucle « for-in ». Par exemple, pour l’objet « File » dont propriétés sont : Le type primitif Symbol() -12/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII ou avec <script type="text/javascript"> console.log(Object.getOwnPropertyDescriptors(File)); </script> Avec Yandex : test.html:2 1. {length: {…}, name: {…}, arguments: {…}, caller: {…}, prototype: {…}} 1. arguments: {value: null, writable: false, enumerable: false, configurable: false} 2. caller: {value: null, writable: false, enumerable: false, configurable: false} 3. length: {value: 2, writable: false, enumerable: false, configurable: tru e} 4. name: {value: "File", writable: false, enumerable: false, configurable : true} 5. prototype: {value: File, writable: false, enumerable: false, configurable: false} 6. __proto__: Object Le type primitif Symbol() -13/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Avec Firefox : <script type="text/javascript"> console.log(Object.keys(File)); </script> <script type="text/javascript"> console.log(Object.values(File)); </script> <script type="text/javascript"> console.log(Object.getOwnPropertyNames(File)); </script> Attention : Le type primitif Symbol() -14/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII « Object.getOwnPropertyNames(File) » ne donne pas le même résultat que « Reflect.ownKeys(File) » : <script type="text/javascript"> console.log(Reflect.ownKeys(File)); </script> <script type="text/javascript"> console.log(Object.getOwnPropertySymbols(File)); </script> La propriété « Symbol . iterator » : Une propriété intéressante de « Symbol » c’est le « Symbol . iterator » qui comme son nom l’indique, permet de générer des « itérables » via une fonction génératrice « function* () » : <script type="text/javascript"> "use strict"; const iterable = new Object(); iterable[Symbol.iterator] = function* () { for(let k=5;k<10;k++)yield {a:k , b:k*k}; }; console.log([...iterable]); // Array(5) [ {…}, {…}, {…}, {…}, {…} ] // (5) […] // 0: Object { a: 5, b: 25 } // 1: Object { a: 6, b: 36 } Le type primitif Symbol() -15/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII // 2: Object { a: 7, b: 49 } // 3: Object { a: 8, b: 64 } // 4: Object { a: 9, b: 81 } // length: 5 // <prototype>: Array [] </script> Ci-dessous, quelques types natifs (=incorporées, " built-in types") ayant par défaut le comportement d’itération : Array . prototype [@@iterator]() TypedArray . prototype [@@iterator]() String . prototype [@@iterator]() Map . prototype [@@iterator]() Set . prototype [@@iterator]() Structure interne de Symbol : Le type primitif Symbol() -16/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Exemples d’utilisation de « Symbol » : Exemple1 : <script type="text/javascript"> const RED = Symbol('red'); const ORANGE = Symbol('Orange'); const YELLOW = Symbol('Yellow'); const GREEN = Symbol('Green'); const BLUE = Symbol('Blue'); const VIOLET = Symbol('Violet'); const a=[ RED,ORANGE,YELLOW,GREEN,BLUE,VIOLET, Symbol("GARBAGE") ]; function coulComplement(color) { switch (color) { case RED: fgo(color, GREEN);break; case ORANGE: fgo(color, BLUE);break; case YELLOW: fgo(color, VIOLET);break; case GREEN: fgo(color, RED);break; Le type primitif Symbol() -17/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII case BLUE: fgo(color, ORANGE);break; case VIOLET: fgo(color, YELLOW);break; default: console.log(color, ' - Unknown color Symbol'); } } function fgo(cl,cp){ console.log( `Complément de ${String(cl)} = ${cp.toString()}` ); } for(i in a)coulComplement(a[i]); </script> Exemple2 : <script type="text/javascript"> "use strict"; var idxv = Symbol('qcmV'); console.log(idxv); // Symbol(qcmV) const idxc = Symbol('qcmC'); console.log(idxc); // Symbol(qcmC) const a = [68, 80, 55]; console.log(a, ` , a.length = ${a.length}`); // Array(3) [ 68, 80, 55 ] , a.length = 3 a[idxv]= 71; console.log(a, ` , a.length = ${a.length}`); Le type primitif Symbol() -18/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII // Array(3) [ 68, 80, 55 ] , a.length = 3 console.log(`a[idxv] = `, a[idxv]); // a[idxv] = 71 a[idxv]= 42; // Écrasement de a[idxv] console.log(a, ` , a.length = ${a.length}`); // Array(3) [ 68, 80, 55 ] , a.length = 3 console.log(`a[idxv] = `, a[idxv]); // a[idxv] = 42 a[idxc]= 29; console.log(a, ` , a.length = ${a.length}`); // Array(3) [ 68, 80, 55 ] , a.length = 3 console.log(`a[idxc] = `, a[idxc]); // a[idxc] = 29 a[idxc]= 46; // Écrasement de a[idxc] console.log(a, ` , a.length = ${a.length}`); // Array(3) [ 68, 80, 55 ] , a.length = 3 console.log(`a[idxc] = `, a[idxc]); // a[idxc] = 46 a[a.length]= 95; console.log(a, ` , a.length = ${a.length}`); // Array(4) [ 68, 80, 55, 95 ] , a.length = 4 console.log(`a[a.length] = `, a[a.length]); // a[a.length] = undefined console.log(`a[a.length] = , ${a[a.length]}`); // a[a.length] = undefined console.log(`a[a.length] = , a${[a.length]}`); // a[a.length] = undefined console.log(`a[4] = `, a[4]); // a[4] = undefined Le type primitif Symbol() -19/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII console.log(`a[idxv] = `, a[idxv]); // a[idxv] = 42 console.log(`a[Symbol('1')] = `, a[Symbol('1')]); // a[Symbol('1')] = undefined console.log(`a["Symbol('1')"] = `, a["Symbol('1')"]); // a["Symbol('1')"] = undefined console.log(`a[Symbol(1)] = `, a[Symbol(1)]); // a[Symbol(1)] = undefined console.log(`a["Symbol(1)"] = `, a["Symbol(1)"]); // a["Symbol(1)"] = undefined console.log(`(a[eval(Symbol('1'))]) = `, (a[eval(Symbol('1'))])); // => (a[eval(Symbol('1'))]) = undefined console.log(`eval(a[(Symbol('1'))]) = `, eval(a[(Symbol('1'))])); // => eval(a[(Symbol('1'))]) = undefined console.log(`Symbol.keyFor(idxv) = `, Symbol.keyFor(idxv)); // => Symbol.keyFor(idxv) = undefined console.log(`a[(Symbol.keyFor(idxv))] = `, a[(Symbol.keyFor(idxv))]); // => a[(Symbol.keyFor(idxv))] = undefined console.log(`Object.keys(a) = ${Object.keys(a)}`); // => Object.keys(a) = 0,1,2,3 console.log(`Object.getOwnPropertyNames(a) = `, Object.getOwnPropertyNames(a)); // => Array(5) [ "0", "1", "2", "3", "length" ] console.log(`Object.getOwnPropertySymbols(a) = `, Object.getOwnPropertySymbols(a)); // => Array [ Symbol(qcmV), Symbol(qcmC) ] console.log(`Reflect.ownKeys(a) = `, Le type primitif Symbol() -20/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Reflect.ownKeys(a)); // Array(7) [ "0", "1", "2", "3", "length", Symbol(qcmV), Symbol(qcmC) ] console.log(Object.entries(a)); // Array(4) [ (2) […], (2) […], (2) […], (2) […] ] </script> Exemple dans une fonction : Création, utilisation, contraintes et restrictions. <script type="text/javascript"> "use strict"; var Elenge = (function () { var KOMBO = Symbol('kombo'); var MBOKA = Symbol('mboka'); function Elenge(kombo, pName) { this[KOMBO] = kombo; this[MBOKA] = pName; } Elenge.prototype.dispKombo = function () { console.log( Le type primitif Symbol() -21/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII "=> Dans Elenge.prototype.dispKombo"); return this[KOMBO]; // Lors de l'appel }; Elenge.prototype.dispMboka = function () { console.log( "=> Dans Elenge.prototype.dispMboka"); return this[MBOKA]; // Lors de l'appel }; return Elenge; })(); // Lors de l'instanciation console.log("Départ"); var motu = new Elenge('Kele', 'Lobiko'); console.log(motu.dispKombo(), motu.dispMboka()); // => Kele Lobiko let t = ""; for (var key in motu) t += key + ` | ` console.log(t); // => dispKombo | dispMboka | // Les Symbols ne sont pas énumerables console.log(motu["kombo"]); console.log(motu["KOMBO"]); // => undefined // => undefined // Les symboles sont uniques console.log(motu[Symbol('kombo')]); console.log(motu[Symbol('KOMBO')]); // => undefined // => undefined console.log(Object.getOwnPropertySymbols(Elenge)); // => Array [] </script> Le type primitif Symbol() -22/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Dommage, l’Array des « Symbol » est vide. Le type primitif Symbol() -23/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Exemple dans un object : <script type="text/javascript"> "use strict"; var O = {annee: 2018}; Object.defineProperty(O, 'mois', {value: 12}); O[Symbol('jour')] = 8; O[Symbol('heure')] = Date.now; console.log(`Object.keys(O) = ${Object.keys(O)}`); // => annee console.log(`Object.getOwnPropertyNames(O) = `, Object.getOwnPropertyNames(O)); // => Array [ "annee", "mois" ] console.log(`Object.getOwnPropertySymbols(O) = `, Object.getOwnPropertySymbols(O)); // => Array [ Symbol(jour) ] console.log(`Reflect.ownKeys(O) = `, Reflect.ownKeys(O)); // => Array(3) [ "annee", "mois", Symbol(jour) ] </script> Le type primitif Symbol() -24/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Quelques méthodes de « Symbol » : <script type="text/javascript"> "use strict"; var Elenge = (function () { var KOMBO = Symbol('kombo'); var MBOKA = Symbol('mboka'); function Elenge(kombo, pName) { this[KOMBO] = kombo; this[MBOKA] = pName; } Elenge.prototype.dispKombo = function () { console.log( "=> Dans Elenge.prototype.dispKombo"); return this[KOMBO]; // Lors de l'appel Le type primitif Symbol() -25/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII }; Elenge.prototype.dispMboka = function () { console.log( "=> Dans Elenge.prototype.dispMboka"); return this[MBOKA]; // Lors de l'appel }; return Elenge; })(); // Lors de l'instanciation console.log("Départ"); var motu = new Elenge('Kele', 'Lobiko'); console.log(motu.dispKombo(), motu.dispMboka()); // => Kele Lobiko console.log(motu["kombo"]); console.log(motu["KOMBO"]); // => undefined // => undefined // Les symboles sont uniques console.log(motu[Symbol('kombo')]); // => undefined console.log(motu[Symbol('KOMBO')]); // => undefined console.log(Object.getOwnPropertySymbols(Elenge)); // => Array [] var t = ""; for (var key in motu) t += key + ` | `; console.log(t); // => dispKombo | dispMboka | // Les Symbols ne sont pas énumerables var keysymb = Symbol.for("motu"); console.log(`« keysymb === Symbol.for("motu") » = ` , keysymb === Symbol.for("motu")); // true console.log(`keysymb = ` , keysymb); // Symbol(motu) console.log(`Symbol.for("motu") = `, Symbol.for("motu")); // Symbol(motu) console.log(`Symbol.keyFor(keysymb) = `, Symbol.keyFor(keysymb)); // motu var t=""; Le type primitif Symbol() -26/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII for (var y in Symbol.keyFor(keysymb)) t += y + ` | `; console.log(t); // => 0 | 1 | 2 | 3 | var t=""; for (var i in Symbol.keyFor(keysymb)) t += Symbol.keyFor(keysymb)[i] + ` | `; console.log(t); // => m | o | t | u | </script> Le type primitif Symbol() -27/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Kinshasa, le jeudi 4 avril 2019 - 10:43:53 PM Mots-clés : Reflect,Symbol,key,keyFor,iterator,generator,function*,toString,prototype, type primitif,built-in,incorporé 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-LaCreation Le type primitif Symbol() -28/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII D’autres publications pouvant aussi intéresser : • https://www.scribd.com/document/377036251/LeDosage-Des-Medicaments-en-Cac-Cas • https://www.scribd.com/document/377035454/LeHasard-Des-Thermometres-Non-contact-a-Infrarouge • https://www.scribd.com/document/376222482/PetiteIntroduction-Aux-Fonctions-JavaScript • https://www.scribd.com/document/376221919/La-Foien-Jesus-Christ-Pour-Quoi-Faire • https://www.scribd.com/document/375689778/Lacuitevisuelle-angulaire • https://www.scribd.com/document/375349851/Lavariable-This • 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/Iterationsen-JavaScript • 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-ObjetLe type primitif Symbol() -29/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Global-Window • https://www.scribd.com/document/372665249/JavascriptTome-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/Renseigne ments-Id-et-Anthropometriques • https://www.scribd.com/document/320856721/Emission31-Jul-2016 • https://www.scribd.com/document/318182982/Complicati on-Visuelle-du-Traitement-de-La-Malaria • https://www.scribd.com/document/318180637/RapportEntre-Oxymetrie-Et-Type-Respiration • https://www.scribd.com/document/315746265/Classificati on-Des-Medicaments • https://www.scribd.com/document/315745909/Incongruen ces-Heresies-et-Heterodoxies-de-la-Notion-deLaboratoire • https://www.scribd.com/document/315745725/RapportLe type primitif Symbol() -30/31- jeudi, 4. avril 2019 (10:43 ) J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII Entre-Oxymetrie-Et-Type-Respiration Le type primitif Symbol() -31/31- jeudi, 4. avril 2019 (10:43 )