V I I I
Pour Débutants
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).
@@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.
Le type primitif Symbol() -2/31- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
@@hasInstance
[[Symbol.hasInstance]]
* A method that determines if a constructor object recogniz-
es 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 ob-
ject should be flattened to its array elements by Ar-
ray.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 ex-
pression against a string.
Called by the String.prototype.match method.
@@replace
[[Symbol.replace]]
* A regular expression method that replaces matched sub-
strings of a string. Called by the String.prototype.replace
method.
@@search
Le type primitif Symbol() -3/31- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
[[Symbol.search]]
* A regular expression method that returns the index within
string that matches the regular expression.
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 indi-
cates that match the regular expression. Called by the
String.prototype.split method.
@@toPrimitive
[[Symbol.toPrimitive]]
* A method that converts an object to a corresponding primi-
tive 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 prop-
erty names are property names that are excluded from the
with environment binding of the associated object.
Le type primitif Symbol() -4/31- dimanche, 24. mars 2019 (12:24 )
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);
// 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, config-
urable: false}
1: {value: "y", writable: false, enumerable: true, config-
urable: false}
2: {value: "S", writable: false, enumerable: true, config-
urable: false}
3: {value: "t", writable: false, enumerable: true, config-
urable: false}
4: {value: "r", writable: false, enumerable: true, config-
urable: 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"]
Le type primitif Symbol() -6/31- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
console.log(Object.getOwnPropertySymbols(mySymb));
// Array []
console.log(Object.getOwnPropertySymbols(ordStr));
// Array []
</script>
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.
console.log(o.prop1);
// propriété prédéfinie
// Notez le point.
// Solution = Symbole.
let prop1= Symbol("Descripteur");
o[prop1] = "Même ID Sans conflit";
// Notez les brackets.
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 type primitif Symbol() -8/31- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
Les valeurs des symboles sont stockées dans un registre appelé « table
globale de symboles ».
<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>
<script type="text/javascript">
const FOO = Symbol();
const obj = {
[FOO](p) { // Notez les brakets
<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;
}
};
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() ,
console.log(Symbol(),Symbol());
// 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 v="DESCRIPTION";
const vSYMBOL3 = Symbol(v);
const vSYMBOL4 = Symbol(v);
console.log(vSYMBOL3,vSYMBOL4);
// Symbol(DESCRIPTION) Symbol(DESCRIPTION)
console.log(Symbol('Yellow')=Symbol('Yellow'));
// YANDEX : test.html:50
Le type primitif Symbol() -11/31- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
// Uncaught ReferenceError:
// Invalid left-hand side in assignment
// at test.html:50
//
// 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 ».
ou avec
<script type="text/javascript">
console.log(Object.getOwnPropertyDescriptors(File));
</script>
Avec Yandex :
test.html:2
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 :
« 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>
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 }
// 2: Object { a: 7, b: 49 }
// 3: Object { a: 8, b: 64 }
// 4: Object { a: 9, b: 81 }
// length: 5
// <prototype>: Array []
</script>
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- dimanche, 24. mars 2019 (12:24 )
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 :
a[idxv]= 71;
console.log(a, ` , a.length = ${a.length}`);
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
console.log(`a[idxc] = `, a[idxc]);
// a[idxc] = 46
a[a.length]= 95;
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
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- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
Reflect.ownKeys(a));
// Array(7) [ "0", "1", "2", "3", "length", Sym-
bol(qcmV), Symbol(qcmC) ]
console.log(Object.entries(a));
// Array(4) [ (2) […], (2) […], (2) […], (2) […] ]
</script>
Elenge.prototype.dispKombo = function () {
console.log(
Elenge.prototype.dispMboka = function () {
console.log(
"=> Dans Elenge.prototype.dispMboka");
return this[MBOKA]; // Lors de l'appel
};
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(Object.getOwnPropertySymbols(Elenge));
// => Array []
</script>
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>
Elenge.prototype.dispKombo = function () {
console.log(
"=> 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
};
console.log("Départ");
var motu = new Elenge('Kele', 'Lobiko');
console.log(motu.dispKombo(), motu.dispMboka());
// => Kele Lobiko
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
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- dimanche, 24. mars 2019 (12:24 )
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>
Mots-clés :
Reflect,Symbol,key,keyFor,iterator,generator,function*,toString,prototype,
type primitif,built-in,incorporé
diasfb@mail2world.com
Autre Lecture :
https://www.scribd.com/document/374738470/Le-Plus-Grand-Secret-de-La-
Creation
• https://www.scribd.com/document/377036251/Le-
Dosage-Des-Medicaments-en-Cac-Cas
• https://www.scribd.com/document/377035454/Le-
Hasard-Des-Thermometres-Non-contact-a-Infrarouge
• https://www.scribd.com/document/376222482/Petite-
Introduction-Aux-Fonctions-JavaScript
• https://www.scribd.com/document/376221919/La-Foi-
en-Jesus-Christ-Pour-Quoi-Faire
• https://www.scribd.com/document/375689778/Lacuite-
visuelle-angulaire
• https://www.scribd.com/document/375349851/La-
variable-This
•
https://www.scribd.com/document/375024162/Fonctions-
Imbriquees-en-JS
• https://www.scribd.com/document/374789297/Format-
Interne-Des-Objets-JavaScript
•
https://www.scribd.com/document/374788758/Iterations-
en-JavaScript
• https://www.scribd.com/document/374738470/Le-Plus-
Grand-Secret-de-La-Creation
• https://www.scribd.com/document/374597969/Nouvelle-
Formule-d-IMC-indice-de-doduite-Selon-Dr-Diasoluka
• https://www.scribd.com/document/373847209/Property-
Descriptors
• https://www.scribd.com/document/373833282/l-Objet-
Le type primitif Symbol() -29/31- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
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-Des-Reflexes-Pupillomoteurs
•
https://www.scribd.com/document/321168468/Renseigne
ments-Id-et-Anthropometriques
•
https://www.scribd.com/document/320856721/Emission-
31-Jul-2016
•
https://www.scribd.com/document/318182982/Complicati
on-Visuelle-du-Traitement-de-La-Malaria
• https://www.scribd.com/document/318180637/Rapport-
Entre-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-de-
Laboratoire
• https://www.scribd.com/document/315745725/Rapport-
Le type primitif Symbol() -30/31- dimanche, 24. mars 2019 (12:24 )
J.D.B. DIASOLUKA Nz. Luyalu JavaScript Tome-VIII
Entre-Oxymetrie-Et-Type-Respiration