Introduction to JavaScript getters and setters in ES6
文章推薦指數: 80 %
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
延伸文章資訊
- 1JavaScript Object Accessors - W3Schools
ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Ob...
- 2JS Getter 與Setter DAY71 - iT 邦幫忙::一起幫忙解決難題
Setter 與Setter Getter: 取得特定值的方法Setter: 存值的方法Getter var wallet = { total: 100, set save(price){ th...
- 37天搞懂JS進階議題(day05)-getter & setter: 屬性描述器
7天搞懂JS進階議題(day05)-getter & setter: 屬性描述器. February 27, 2020. 本系列文章討論JS 物件導向設計相關的特性。 不含CSS,不含HTML!...
- 4setter - JavaScript - MDN Web Docs
最少要有一個參數(請參見Incompatible ES5 change: literal getter and setter functions must now have exactly ze...
- 5[JS] Getter and Setter 筆記 - pcwu's TIL Notes
[JS] Getter and Setter 筆記. 12 Feb 2017. JavaScript. 在JavaScript 中如果Class 在取屬性值或設定屬性值時,如果有比較複雜的運用時...