JavaScript中的作用域englishWord格式.docx
- 文档编号:4586915
- 上传时间:2023-05-03
- 格式:DOCX
- 页数:11
- 大小:25.55KB
JavaScript中的作用域englishWord格式.docx
《JavaScript中的作用域englishWord格式.docx》由会员分享,可在线阅读,更多相关《JavaScript中的作用域englishWord格式.docx(11页珍藏版)》请在冰点文库上搜索。
Let’swalkthroughsomeexamplecodetoexploretheimplications:
<
scripttype="
text/javascript"
>
varima_celebrity="
Everyonecanseeme!
I'
mfamous!
"
the_president="
I'
mthedecider!
;
functionpleasantville(){
varthe_mayor="
IrulePleasantvillewithanironfist!
ima_celebrity="
AllmyneighborsknowwhoIam!
functionlonely_house(){
varagoraphobic="
Ifearthedaystar!
a_cat="
Meow."
}
/script>
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
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(){
vardeep_thought=newBigComputer(42);
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
...
buttonid='
thebutton'
onclick='
click_handler()'
Clickme!
/button>
However,whenweaddaneventhandlerviaJavaScript,thisreferstotheDOMelementthatgeneratedtheevent.(Note:
Theeventhandlingshownhereisshortandreadable,butotherwisepoor.PleaseusearealaddEventfunctioninstead.):
//alertsthebuttonDOMnode
functionaddhandler(){
document.getElementById('
).onclick=click_handler;
window.onload=addhandler;
Complications
Let’srunwiththatlastexampleforamomentlonger.Whatifinsteadofrunningclick_handler,wewantedtoaskdeep_thoughtaquestioneverytimeweclickedthebutton?
Thecodeforthatseemsprettystraightforward;
wemighttrythis:
alert(this.the_answer);
vardeep_thought=newBigComputer(42),
the_button=document.getElementById('
);
the_button.onclick=deep_thought.ask_question;
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