JavaScript中的作用域english.docx

上传人:b****2 文档编号:2473696 上传时间:2023-05-03 格式:DOCX 页数:11 大小:25.55KB
下载 相关 举报
JavaScript中的作用域english.docx_第1页
第1页 / 共11页
JavaScript中的作用域english.docx_第2页
第2页 / 共11页
JavaScript中的作用域english.docx_第3页
第3页 / 共11页
JavaScript中的作用域english.docx_第4页
第4页 / 共11页
JavaScript中的作用域english.docx_第5页
第5页 / 共11页
JavaScript中的作用域english.docx_第6页
第6页 / 共11页
JavaScript中的作用域english.docx_第7页
第7页 / 共11页
JavaScript中的作用域english.docx_第8页
第8页 / 共11页
JavaScript中的作用域english.docx_第9页
第9页 / 共11页
JavaScript中的作用域english.docx_第10页
第10页 / 共11页
JavaScript中的作用域english.docx_第11页
第11页 / 共11页
亲,该文档总共11页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

JavaScript中的作用域english.docx

《JavaScript中的作用域english.docx》由会员分享,可在线阅读,更多相关《JavaScript中的作用域english.docx(11页珍藏版)》请在冰点文库上搜索。

JavaScript中的作用域english.docx

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

  }

 

 ...

 Clickme!

However,whenweaddaneventhandlerviaJavaScript,thisreferstotheDOMelementthatgeneratedtheevent.(Note:

Theeventhandlingshownhereisshortandreadable,butotherwisepoor.PleaseusearealaddEventfunctioninstead.):

 

  functionclick_handler(){

   alert(this);//alertsthebuttonDOMnode

  }

 

  functionaddhandler(){

   document.getElementById('thebutton').onclick=click_handler;

  }

 

  window.onload=addhandler;

 

 ...

 Clickme!

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

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 求职职场 > 简历

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2