JS Hoisting
Basiese Inligting
In die JavaScript-taal word 'n meganisme bekend as Hoisting beskryf waar verklarings van veranderlikes, funksies, klasse of invoere konseptueel na die bokant van hul omvang verhef word voordat die kode uitgevoer word. Hierdie proses word outomaties deur die JavaScript-enjin uitgevoer, wat deur die skrip in verskeie passe gaan.
Tydens die eerste pas, ontleed die enjin die kode om te kyk vir sintaksisfoute en transformeer dit in 'n abstrakte sintaksisboom. Hierdie fase sluit hoisting in, 'n proses waar sekere verklarings na die bokant van die uitvoeringskonteks verskuif word. As die ontledingsfase suksesvol is, wat aandui dat daar geen sintaksisfoute is nie, gaan die skripuitvoering voort.
Dit is van kardinale belang om te verstaan dat:
Die skrip moet vry wees van sintaksisfoute vir uitvoering om plaas te vind. Sintaksisreëls moet streng nagekom word.
Die plasing van kode binne die skrip beïnvloed uitvoering as gevolg van hoisting, alhoewel die uitgevoerde kode mag verskil van sy tekstuele voorstelling.
Tipes Hoisting
Gebaseer op die inligting van MDN, is daar vier duidelike tipes hoisting in JavaScript:
Waarde Hoisting: Maak die gebruik van 'n veranderlike se waarde binne sy omvang moontlik voordat sy verklaringlyn.
Verklaring Hoisting: Laat die verwysing na 'n veranderlike binne sy omvang toe voordat sy verklaring, sonder om 'n
ReferenceError
te veroorsaak, maar die veranderlike se waarde salundefined
wees.Hierdie tipe verander die gedrag binne sy omvang as gevolg van die veranderlike se verklaring voordat sy werklike verklaringlyn.
Die neveneffekte van die verklaring vind plaas voordat die res van die kode wat dit bevat, geëvalueer word.
In detail, funksieverklarings toon tipe 1 hoisting gedrag. Die var
sleutelwoord demonstreer tipe 2 gedrag. Lexikale verklarings, wat let
, const
, en class
insluit, toon tipe 3 gedrag. Laastens, import
verklarings is uniek in die sin dat hulle met beide tipe 1 en tipe 4 gedrag gehoist word.
Scenario's
Daarom, as jy scenario's het waar jy JS kode kan inspuit nadat 'n nie-verklaarde objek gebruik is, kan jy die sintaksis regmaak deur dit te verklaar (sodat jou kode uitgevoer word in plaas daarvan om 'n fout te gooi):
Meer Scenario's
Verwysings
Last updated