JavaScript中的作用域english.docx
- 文档编号:2473696
- 上传时间:2023-05-03
- 格式:DOCX
- 页数:11
- 大小:25.55KB
JavaScript中的作用域english.docx
《JavaScript中的作用域english.docx》由会员分享,可在线阅读,更多相关《JavaScript中的作用域english.docx(11页珍藏版)》请在冰点文库上搜索。
JavaScript中的作用域english
ScopeisoneofthefoundationalaspectsoftheJavaScriptlanguage,andprobablytheoneI’vestruggledwiththemostwhenbuildingcomplexprograms.Ican’tcountthenumberoftimesI’velosttrackofwhatthethiskeywordreferstoafterpassingcontrolaroundfromfunctiontofunction,andI’veoftenfoundmyselfcontortingmycodeinallsortsofconfusingways,tryingtoretainsomesemblanceofsanityinmyunderstandingofwhichvariableswereaccessiblewhere.
Intypicalobject-orientedprogramming,weneedawayofidentifyingandreferringtotheobjectthatwe’recurrentlyworkingwith.thisservesthepurposeadmirably,providingourobjectstheabilitytoexaminethemselves,andpointattheirownproperties.
Thisarticlewilltackletheproblemhead-on,outliningdefinitionsofcontextandscope,examiningtwoJavaScriptmethodsthatallowustomanipulatecontext,andconcludingwithadeepdiveintoaneffectivesolutiontoninetypercentoftheproblemsI’veruninto.
WhereAmI?
AndWhoAreYou?
EverybitofyourJavaScriptprogramisexecutedinoneexecutioncontextoranother.Youcanthinkofthesecontextsasyourcode’sneighborhood,givingeachlineanunderstandingofwhereitcomesfrom,andwhoitsfriendsandneighborsare.Asitturnsout,thisisimportantinformation,asJavaScriptsocietieshavefairlystrictrulesaboutwhocanassociatewithwhom;executioncontextsarebetterthoughtofasgatedcommunitiesthanasopensubdivisions.
Wecanrefertothesesocialboundariesgenerallyasscope,andthey’reimportantenoughtobecodifiedineachneighborhood’scharter,whichwe’llrefertoasthecontext’sscopechain.Codewithinaparticularneighborhoodcanonlyaccessvariableslistedonitsscopechain,andprefersinteractionwithlocalstoassociationsoutsideitsneighborhood.
Practicallyspeaking,evaluatingafunctionestablishesadistinctexecutioncontextthatappendsitslocalscopetothescopechainitwasdefinedwithin.JavaScriptresolvesidentifierswithinaparticularcontextbyclimbingupthescopechain,movinglocallytoglobally.Thismeansthatlocalvariableswiththesamenameasvariableshigheruponthescopechaintakeprecedence,whichmakessense:
Ifmygoodfriendsaretalkingtogetherabout“MikeWest,”it’sprettyclearthatthey’retalkingaboutme,notaboutthebluegrasssingerortheDukeprofessor,eventhoughthelattertwoare(arguably)betterknown.
Let’swalkthroughsomeexamplecodetoexploretheimplications:
varima_celebrity="Everyonecanseeme!
I'mfamous!
",
the_president="I'mthedecider!
";
functionpleasantville(){
varthe_mayor="IrulePleasantvillewithanironfist!
",
ima_celebrity="AllmyneighborsknowwhoIam!
";
functionlonely_house(){
varagoraphobic="Ifearthedaystar!
",
a_cat="Meow.";
}
}
Ourglobalstar,ima_celebrity,isrecognizedbyeveryone.She’spoliticallyactive,talkingwiththe_presidentonafairlyfrequentbasis,andincrediblyfriendly;she’llsignautographsandanswerquestionsforanyonesherunsinto.Thatsaid,shedoesn’thaveawholelotofpersonalcontactwithherfans.She’sprettysuretheyexistandthattheyprobablyhavelivesoftheirownsomewhere,butshecertainlydoesn’tknowwhatthey’redoing,oreventheirnames.
Insidepleasantville,the_mayorisawell-knownface.She’salwayswalkingthestreetsofhertown,chattingupherconstituents,shakinghands,andkissingbabies.Aspleasantvilleisabig,importantneighborhood,she’sgotabigredphoneinheroffice,givingheradirectlinetothepresident(oratleastatopaide)24hoursaday,7daysaweek.She’sseenlonely_houseuponahillattheoutskirtsoftown,butneverreallyworriedaboutwholivesinside.
Thatlonely_houseisaworlduntoitself.Theagoraphobicstaysinsidemostofthetime,playingsolitaireandfeedinga_cat.He’scalledthe_mayorafewtimestoaskaboutlocalnoiseregulations,andevenwroteima_celebrity(Pleasantville’sima_celebrity,thatis)somefanmailafterseeingheronthelocalnews.
this?
What’sthat?
Inadditiontoestablishingascopechain,eachexecutioncontextoffersakeywordnamedthis.Initsmostcommonusage,thisservesasanidentityfunction,providingourneighborhoodsawayofreferringtothemselves.Wecan’talwaysrelyonthatbehavior,however:
Dependingonhowwegetintoaparticularneighborhood,thismightmeansomethingelseentirely.Infact,howwegetintotheneighborhoodisitselfexactlywhatthisgenerallyrefersto.Fourscenariosdeservespecialattention:
∙CallinganObject’sMethod
Intypicalobject-orientedprogramming,weneedawayofidentifyingandreferringtotheobjectthatwe’recurrentlyworkingwith.thisservesthepurposeadmirably,providingourobjectstheabilitytoexaminethemselves,andpointattheirownproperties.
vardeep_thought={
the_answer:
42,
ask_question:
function(){
returnthis.the_answer;
}
};
varthe_meaning=deep_thought.ask_question();
Thisexamplebuildsanobjectnameddeep_thought,setsitsthe_answerpropertyto42,andcreatesanask_questionmethod.Whendeep_thought.ask_question()isexecuted,JavaScriptestablishesanexecutioncontextforthefunctioncall,settingthistotheobjectreferencedbywhatevercamebeforethelast”.”,inthiscase:
deep_thought.Themethodcanthenlookinthemirrorviathistoexamineitsownproperties,returningthevaluestoredinthis.the_answer:
42.
∙Constructor
Likewise,whendefiningafunctiontobeusedasaconstructorwiththenewkeyword,thiscanbeusedtorefertotheobjectbeingcreated.Let’srewritetheexampleabovetoreflectthatscenario:
functionBigComputer(answer){
this.the_answer=answer;
this.ask_question=function(){
returnthis.the_answer;
}
}
vardeep_thought=newBigComputer(42);
varthe_meaning=deep_thought.ask_question();
Insteadofexplicitlycreatingthedeep_thoughtobject,we’llwriteafunctiontocreateBigComputerobjects,andinstantiatedeep_thoughtasaninstancevariableviathenewkeyword.WhennewBigComputer()isexecuted,acompletelynewobjectiscreatedtransparentlyinthebackground.BigComputeriscalled,anditsthiskeywordissettoreferencethatnewobject.Thefunctioncansetpropertiesandmethodsonthis,whichistransparentlyreturnedattheendofBigComputer’sexecution.
Notice,though,thatdeep_thought.the_question()stillworksjustasitdidbefore.What’sgoingonthere?
Whydoesthismeansomethingdifferentinsidethe_questionthanitdoesinsideBigComputer?
Putsimply,weenteredBigComputervianew,sothismeant“thenewobject.”Ontheotherhand,weenteredthe_questionviadeep_thought,sowhilewe’reexecutingthatmethod,thismeans“whateverdeep_thoughtrefersto”.thisisnotreadfromthescopechainasothervariablesare,butinsteadisresetonacontextbycontextbasis.
∙FunctionCall
Whatifwejustcallanormal,everydayfunctionwithoutanyofthisfancyobjectstuff?
Whatdoesthismeaninthatscenario?
functiontest_this(){
returnthis;
}
vari_wonder_what_this_is=test_this();
Inthiscase,weweren’tprovidedacontextbynew,norwerewegivenacontextintheformofanobjecttopiggybackoffof.Here,thisdefaultstoreferencethemostglobalthingitcan:
forwebpages,thisisthewindowobject.
∙EventHandler
Foramorecomplicatedtwistonthenormalfunctioncall,let’ssaythatwe’reusingafunctiontohandleanonclickevent.Whatdoesthismeanwhentheeventtriggersourfunction’sexecution?
Unfortunately,there’snotasimpleanswertothisquestion.
Ifwewritetheeventhandlerinline,thisreferstotheglobalwindowobject:
functionclick_handler(){
alert(this);//alertsthewindowobject
}
...
However,whenweaddaneventhandlerviaJavaScript,thisreferstotheDOMelementthatgeneratedtheevent.(Note:
Theeventhandlingshownhereisshortandreadable,butotherwisepoor.PleaseusearealaddEventfunctioninstead.):
functionclick_handler(){
alert(this);//alertsthebuttonDOMnode
}
functionaddhandler(){
document.getElementById('thebutton').onclick=click_handler;
}
window.onload=addhandler;
...
Complications
Let’srunwiththatlastexampleforamomentlonger.Whatifinsteadofrunningclick_handler,wewantedtoaskdeep_thoughtaquestioneverytimeweclickedthebutton?
Thecodeforthatseemsprettystraightforward;wemighttrythis:
functionBigComputer(answer){
this.the_answer=answer;
this.ask_question=function(){
alert(this.the_answer);
}
}
functionaddhandler(){
vardeep_thought=newBigComputer(42),
the_button=document.getElementById('thebutton');
the_button.onclick=deep_thought.ask_question;
}
window.onload=addhandler;
Perfect,right?
Weclickonthebutton,deep_thought.ask_questionisexecuted,andwegetback“42.”Sowhyisthebrowsergivingusundefinedinstead?
Whatdidwedowrong?
Theproblemissimplythis:
We’vepassedoffareferencetotheask_questionmethod,which,whenexecutedasaneventhandler,runsinadifferentcontextthanwhenit’sexecutedasanobjectmethod.Inshort,thethis
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- JavaScript 中的 作用 english