Está en la página 1de 4

Top4JavascriptConceptsaNode.

jsBeginnerMust
Know
Wouldntitbeawesomeifyouonlyhadtoknowoneprogramminglanguageforbuildingafullstack
application?RyanDahlputthisthoughtintoactionandcreatedNode.js.Node.jsisaserverside
frameworkthatisbuiltuponChromespowerfulV8JavaScriptengine.ThoughoriginallywritteninC++,it
usesJavaScripttobeusedinapplications.
See,problemsolved.Onelanguagetorulethemall.Butthisalsobringsyoudowntothefactthatnow
yourwholeapplicationisusingthesamelanguage.Thatmeansyoumusthaveasoundknowledgeof
thatlanguage.
HerearethefourbareminimumconceptsthatyoushouldbeabletoputinpracticetouseNode.js
effectively.

1.NonblockingorAsynchronousI/O
SinceNode.jsisaserversideframework,oneofitsmainoperationsistohandlebrowserrequests.In
traditionalI/Osystems,arequestcanonlybeissuedwhentheresponse(theHTMLpage)ofthe
previousrequesthasarrived.Theserverblocksotherrequests,calledblockingI/O,inordertoprocess
thecurrentrequest,whichcausesthebrowsertowait(therotatingcircle).
Node.jsdoesntfollowthisprincipleofI/O.Ifarequestisintendedtotakelonger,Nodesendsthat
requestinaneventloop(whichIllexplainingreaterdepthinadifferentarticle)andgoesontohandle
thenextrequestinthecallstack.Assoonasthependingrequestisdoneprocessing,ittellsNode.js
andtheresponseisrenderedonthebrowser.
Letsunderstandthiswithadummyexample:

BlockingI/O
Inthisexampleofarestaurant,thewaitertakesanorder,waitsfortheordertocomplete,andthengoes
backtothetabletoservetheordereachtime.Duringthetimetheorderisprocessing,thewaiterjust
waitsorblocksordersfromothercustomers.

NonblockingI/O
Inthisexample,thewaitertakesanorder,informsthecookofthatorder,andgoesbacktotakeanother
order.Afterthefirstorderisdoneprocessing,thewaitertakesthatordertotherespectivetableand
goesonagaintotakeordersfromothercustomers.Incontrastwiththefirstexample,thewaiterdoesnt

blockordersfromothercustomers.

2.Prototype
PrototypeisacomplexconceptofJavaScript.SinceyouaregoingtouseprototypesalotinNode.js,
everyJavascriptdevelopermustknowaboutthisconcept.
InalanguagethatimplementsclassicalinheritancelikeJavaorC++,forthepurposeofcodereuse,you
firstmakeaclass(ablueprintforyourobjects)andthenyoucreateobjectsfromthatclassorextend
thatclasstoinherititsproperties.
ButthereisnoconceptofclassesinJavaScript.YoufirstcreateanobjectinJavaScriptandthen
augmentyourownobjectorcreatenewobjectsfromit.Thisiscalledprototypalinheritance,meaning
thatobjectsareimplementedthroughtheprototype,notthroughclasses.
EveryJavaScriptobjectislinkedtoaprototypeobjectfromwhichitcaninheritproperties.Prototypesare
analogoustoclassesinotherOOlanguagesbutdifferinthefactthattheyareobjectsthemselves.Every
objectislinkedtoObject.prototypewhichcomespredefinedwithJavaScript.
Ifyoulookupapropertyviaobj.propNameorobj[propName]andtheobjectdoesnothavesucha
propertywhichcanbecheckedviaobj.hasOwnProperty(propName),thentheJavaScriptsruntime
looksupthepropertyinitsprototypeobject.Iftheprototypeobjectalsodoesnthavesuchaproperty,its
ownprototypeischeckedinturnuntilamatchisfoundorifithasreachedObject.prototype.Ifthat
propertydoesntexistintheprototypechain,thenitresultsinanundefinedvalue.
Letsillustratethatwiththefollowingsamplecode:
Whenyoumakeanewobject,youcanselectanobjectthatshouldbeitsprototype.Here,weareadding
acreatemethodtotheObjectfunction.Thecreatemethodcreatesanewobjectthatusesanother
objectasitsprototypebypassingtheotherobjectasanargumenttothecreatemethod.Whenwemake
changestothenewobject,itsprototyperemainsunaffected.Butwhenwemakechangestothe
prototypeobject,thechangesbecomesvisibleinalltheobjectsthatarebasedonthatprototype.
Prototypeisacomplexconcept.Illbediscussingitindetailinanotherpost.

3.Modules
IfyouveeverworkedwithpackagesinJava,modulesinNode.jsisnodifferent.Ifyouhavent,dont
worry.ModulesaresimpleJavaScriptfilesthatcontaincodeforaspecificpurpose.Themodulepattern
isusedtomakeyourcodeeasytonavigateandworkwith.Tousethepropertiesofamodule,youhave
torequireitinaJavaScriptfilemuchlikethesameasyouimportpackagesinaJavaclass.Thereare
twotypesofmodulesinNode.js:

CoreModulesThesearetheonesthatcomeprecompiledwiththeNode.jslibrary.Thepurposeof
coremodulesistoprovidedeveloperswithoftenoccurringandrepeatingcodesectionsthat,ifthey
werenotavailable,wouldresultinatedioustaskfordevelopersbecausetheyhavetowritethesame
codeagainandagain.SomecommoncoremodulesareHTTP,URL,EVENTS,FILESYSTEM,etc.
UserDefinedModulesUserdefinedmodulesaretheoneswhichadevelopermakesforaspecific
purposeinhis/herapplication.Thesearerequiredwhenthecoremodulesarenotcapableoffulfilling
thedesiredfunctionality.
Modulesareextractedviatherequirefunction.Ifitsacoremodule,theargumentissimplythenameof
thatmodule.Ifitsauserdefinedmodule,thentheargumentisthepathofthatmoduleinthefile
system.Forexample,

4.Callbacks
InJavaScript,functionsareregardedasfirstclassobjects.Thatmeansyoucandoalltheoperations
withafunctionthatyoucandowithregularobjects.Youcanassignfunctionstoavariable,passthese
asargumentstomethods,declarethemasapropertyofanobject,andevenreturnthemfrom
functions.
Callbacks,themostwidelyusedfunctionalprogrammingparadigm,areanonymousfunctionsin
JavaScriptthatcanbepassedasargumentstootherfunctionsandcanbeexecutedorreturnedfrom
thatfunctiontobeexecutedlater.
Whenwepassacallbackfunctionasanargumenttoanotherfunction,weonlypassthefunction
definition,i.e.,weneverknowwhenthatcallbackfunctionwillexecute.Thetimingoftheexecutionsolely
dependsonthemechanismofthecallingfunction.Itiscalledbackatsomelaterpointoftime,hence
thename.ThatsthesolebasisofthenonblockingorasynchronousbehaviorofNode.jsasillustrated
bythefollowingexample.
Thisisoneofthesimplestexampleofacallback.Wepassedananonymousfunctionasanargument,
whichsimplylogssomeoutputontheconsoletothesetTimeoutfunction.Sinceitsonlythefunction
definition,thefunctiondoesntknowwhentoexecute.Theexecutiontimeisdeterminedbythecalling
setTimeoutfunctionviathesecondargument,whichdeterminesthatitwillbeexecutedafter2seconds.
First,thesecondlogstatementlogstheoutputtotheconsoleandthenaftertwoseconds,thelog
statementinthecallbackfunctionlogstheoutput.
Thatsit.ThesearemytopfourJavaScriptconceptswhichNode.jsbeginnerswouldbewisetolearnto
bebetterprogrammers.
Whatisinyourlist?Pleasetellmeinthecomments.

Reference:
JuniorWebDeveloperAmadeusITGroup
SaltLakeCity,UT
Feb,20

También podría gustarte