⊗jsSpSyOF 55 of 294 menu

Function in an object in JavaScript

Using symbols, functions can be added to objects and these functions will not participate in the looping. Let's try. Let's have an object:

let obj = {a: 1, b: 2, c: 3};

Let's create a symbol:

let sym = Symbol();

Write a function to an object with a key in the form of our symbol:

obj[sym] = function() { console.log('!!!'); };

When iterating over the object, our function will not be iterated:

for (let key in obj) { console.log(obj[key]); // 1, 2, 3 }

We get our function by passing our symbol (the same variable) as a key:

let func = obj[sym]; func();

We can shorten the code:

obj[sym]();

Add a function to the object that will display the current time. Call this function.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline