Introduction to JavaScript getters and setters in ES6

文章推薦指數: 80 %
投票人數:10人

Use the get and set keywords to define the JavaScript getters and setters for a class or an object. · The get keyword binds an object property to a method that ... SkiptocontentHome»JavaScriptTutorial»JavaScriptGettersandSettersSummary:inthistutorial,youwilllearnaboutJavaScriptgettersandsettersandhowtousethemeffectively.IntroductiontotheJavaScriptgettersandsettersThefollowingexampledefinesaclasscalledPerson:classPerson{ constructor(name){ this.name=name; } } letperson=newPerson("John"); console.log(person.name);//John Codelanguage:JavaScript(javascript)ThePersonclasshasapropertynameandaconstructor.Theconstructorinitializesthenamepropertytoastring.Sometimes,youdon’twantthenamepropertytobeaccesseddirectlylikethis:person.nameCodelanguage:CSS(css)Todothat,youmaycomeupwithapairofmethodsthatmanipulatethenameproperty.Forexample:classPerson{ constructor(name){ this.setName(name); } getName(){ returnthis.name; } setName(newName){ newName=newName.trim(); if(newName===''){ throw'Thenamecannotbeempty'; } this.name=newName; } } letperson=newPerson('JaneDoe'); console.log(person);//JaneDoe person.setName('JaneSmith'); console.log(person.getName());//JaneSmithCodelanguage:JavaScript(javascript)Inthisexample,thePersonclasshasthenameproperty.Also,ithastwoadditionalmethodsgetName()andsetName().ThegetName()methodreturnsthevalueofthenameproperty.ThesetName()methodassignsanargumenttothenameproperty.ThesetName()removesthewhitespacesfrombothendsofthenewNameargumentandthrowsanexceptionifthenewNameisempty.Theconstructor()callsthesetName()methodtoinitializethenameproperty:constructor(name){ this.setName(name); }Codelanguage:JavaScript(javascript)ThegetName()andsetName()methodsareknownasgetterandsetterinotherprogramminglanguagessuchasJavaandC++.ES6providesspecificsyntaxfordefiningthegetterandsetterusingthegetandsetkeywords.Forexample:classPerson{ constructor(name){ this.name=name; } getname(){ returnthis._name; } setname(newName){ newName=newName.trim(); if(newName===''){ throw'Thenamecannotbeempty'; } this._name=newName; } }Codelanguage:JavaScript(javascript)Howitworks.First,thenamepropertyischangedto_nametoavoidthenamecollisionwiththegetterandsetter.Second,thegetterusesthegetkeywordfollowedbythemethodname:getname(){ returnthis._name; }Codelanguage:JavaScript(javascript)Tocallthegetter,youusethefollowingsyntax:letname=person.name;Codelanguage:JavaScript(javascript)WhenJavaScriptseestheaccesstonamepropertyofthePersonclass,itchecksifthePersonclasshasanynameproperty.Ifnot,JavaScriptchecksifthePersonclasshasanymethodthatbindstothenameproperty.Inthisexample,thename()methodbindstothenamepropertyviathegetkeyword.OnceJavaScriptfindsthegettermethod,itexecutesthegettermethodandreturnsavalue.Third,thesetterusesthesetkeywordfollowedbythemethodname:setname(newName){ newName=newName.trim(); if(newName===''){ throw'Thenamecannotbeempty'; } this._name=newName; }Codelanguage:JavaScript(javascript)JavaScriptwillcallthename()setterwhenyouassignavaluetothenamepropertylikethis:person.name='JaneSmith';Codelanguage:JavaScript(javascript)Ifaclasshasonlyagetterbutnotasetterandyouattempttousethesetter,thechangewon’ttakeanyeffect.Seethefollowingexample:classPerson{ constructor(name){ this._name=name; } getname(){ returnthis._name; } } letperson=newPerson("JaneDoe"); console.log(person.name); //attempttochangethename,butcannot person.name='JaneSmith'; console.log(person.name);//JaneDoeCodelanguage:JavaScript(javascript)Inthisexample,thePersonclasshasthenamegetterbutnotthenamesetter.Itattemptstocallthesetter.However,thechangedoesn’ttakeeffectsincethePersonclassdoesn’thavethenamesetter.UsinggetterinanobjectliteralThefollowingexampledefinesagettercalledlatesttoreturnthelatestattendeeofthemeetingobject:letmeeting={ attendees:[], add(attendee){ console.log(`${attendee}joinedthemeeting.`); this.attendees.push(attendee); returnthis; }, getlatest(){ letcount=this.attendees.length; returncount==0?undefined:this.attendees[count-1]; } }; meeting.add('John').add('Jane').add('Peter'); console.log(`Thelatestattendeeis${meeting.latest}.`);Codelanguage:JavaScript(javascript)Output:Johnjoinedameeting. Janejoinedameeting. Peterjoinedameeting. ThelatestattendeeisPeter.SummaryUsethegetandsetkeywordstodefinetheJavaScriptgettersandsettersforaclassoranobject.Thegetkeywordbindsanobjectpropertytoamethodthatwillbeinvokedwhenthatpropertyislookedup.Thesetkeywordbindsanobjectpropertytoamethodthatwillbeinvokedwhenthatpropertyisassigned.PreviouslyJavaScriptClassUpNextJavaScriptClassExpressionsSearchfor:GettingStartedJavaScriptFundamentalsJavaScriptOperatorsControlFlowJavaScriptFunctionsJavaScriptObjectsClassesAdvancedFunctionsPromises&Async/AwaitJavaScriptModulesJavascriptErrorHandlingJavaScriptRuntime



請為這篇文章評分?