JavaScript Tutorial => Getters and Setters

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

In a class definition, a getter is written like a no-argument method prefixed by the get keyword. A setter is similar, except that it accepts one argument (the ... DownloadJavaScript(PDF) JavaScript GettingstartedwithJavaScript AwesomeBook AwesomeCommunity AwesomeCourse AwesomeTutorial AwesomeYouTube .postMessage()andMessageEvent AJAX Anti-patterns Arithmetic(Math) Arrays ArrowFunctions Asyncfunctions(async/await) AsyncIterators AutomaticSemicolonInsertion-ASI BatteryStatusAPI BehavioralDesignPatterns BinaryData Bitwiseoperators BitwiseOperators-RealWorldExamples(snippets) BOM(BrowserObjectModel) Built-inConstants Callbacks Classes ClassConstructor ClassInheritance ClassNamebinding DynamicMethodNames GettersandSetters ManagingPrivateDatawithClasses Methods PrivateMembers StaticMethods Comments ComparisonOperations Conditions Console Constructorfunctions Context(this) Cookies CreationalDesignPatterns CustomElements Dataattributes DataManipulation DatatypesinJavascript Date DateComparison Debugging DeclarationsandAssignments Destructuringassignment Detectingbrowser Enumerations ErrorHandling EscapeSequences EvaluatingJavaScript Events execCommandandcontenteditable Fetch FileAPI,BlobsandFileReaders FluentAPI FunctionalJavaScript Functions Generators Geolocation Globalerrorhandlinginbrowsers History Howtomakeiteratorusableinsideasynccallbackfunction IndexedDB Inheritance IntervalsandTimeouts JavaScriptVariables JSON Linters-Ensuringcodequality Localization Loops Map Memoryefficiency MethodChaining Modals-Prompts ModularizationTechniques Modules Namespacing NavigatorObject NotificationsAPI Objects PerformanceTips Promises Prototypes,objects Proxy Regularexpressions requestAnimationFrame ReservedKeywords SameOriginPolicy&Cross-OriginCommunication Scope Screen Securityissues SelectionAPI Server-sentevents Set SettersandGetters Strictmode Strings Symbols TailCallOptimization TemplateLiterals TheEventLoop Tilde~ Timestamps Transpiling UnaryOperators UnitTestingJavascript Usingjavascripttoget/setCSScustomvariables Variablecoercion/conversion VibrationAPI WeakMap WeakSet WebCryptographyAPI WebStorage WebSockets Workers JavaScript GettingstartedwithJavaScript AwesomeBook AwesomeCommunity AwesomeCourse AwesomeTutorial AwesomeYouTube .postMessage()andMessageEvent AJAX Anti-patterns Arithmetic(Math) Arrays ArrowFunctions Asyncfunctions(async/await) AsyncIterators AutomaticSemicolonInsertion-ASI BatteryStatusAPI BehavioralDesignPatterns BinaryData Bitwiseoperators BitwiseOperators-RealWorldExamples(snippets) BOM(BrowserObjectModel) Built-inConstants Callbacks Classes ClassConstructor ClassInheritance ClassNamebinding DynamicMethodNames GettersandSetters ManagingPrivateDatawithClasses Methods PrivateMembers StaticMethods Comments ComparisonOperations Conditions Console Constructorfunctions Context(this) Cookies CreationalDesignPatterns CustomElements Dataattributes DataManipulation DatatypesinJavascript Date DateComparison Debugging DeclarationsandAssignments Destructuringassignment Detectingbrowser Enumerations ErrorHandling EscapeSequences EvaluatingJavaScript Events execCommandandcontenteditable Fetch FileAPI,BlobsandFileReaders FluentAPI FunctionalJavaScript Functions Generators Geolocation Globalerrorhandlinginbrowsers History Howtomakeiteratorusableinsideasynccallbackfunction IndexedDB Inheritance IntervalsandTimeouts JavaScriptVariables JSON Linters-Ensuringcodequality Localization Loops Map Memoryefficiency MethodChaining Modals-Prompts ModularizationTechniques Modules Namespacing NavigatorObject NotificationsAPI Objects PerformanceTips Promises Prototypes,objects Proxy Regularexpressions requestAnimationFrame ReservedKeywords SameOriginPolicy&Cross-OriginCommunication Scope Screen Securityissues SelectionAPI Server-sentevents Set SettersandGetters Strictmode Strings Symbols TailCallOptimization TemplateLiterals TheEventLoop Tilde~ Timestamps Transpiling UnaryOperators UnitTestingJavascript Usingjavascripttoget/setCSScustomvariables Variablecoercion/conversion VibrationAPI WeakMap WeakSet WebCryptographyAPI WebStorage WebSockets Workers JavaScript Classes GettersandSetters Example Gettersandsettersallowyoutodefinecustombehaviourforreadingandwritingagivenpropertyonyourclass.Totheuser,theyappearthesameasanytypicalproperty.However,internallyacustomfunctionyouprovideisusedtodeterminethevaluewhenthepropertyisaccessed(thegetter),andtopreformanynecessarychangeswhenthepropertyisassigned(thesetter). Inaclassdefinition,agetteriswrittenlikeano-argumentmethodprefixedbythegetkeyword.Asetterissimilar,exceptthatitacceptsoneargument(thenewvaluebeingassigned)andthesetkeywordisusedinstead. Here'sanexampleclasswhichprovidesagetterandsetterforits.nameproperty.Eachtimeit'sassigned,we'llrecordthenewnameinaninternal.names_array.Eachtimeit'saccessed,we'llreturnthelatestname. classMyClass{ constructor(){ this.names_=[]; } setname(value){ this.names_.push(value); } getname(){ returnthis.names_[this.names_.length-1]; } } constmyClassInstance=newMyClass(); myClassInstance.name='Joe'; myClassInstance.name='Bob'; console.log(myClassInstance.name);//logs:"Bob" console.log(myClassInstance.names_);//logs:["Joe","Bob"] Ifyouonlydefineasetter,attemptingtoaccessthepropertywillalwaysreturnundefined. constclassInstance=newclass{ setprop(value){ console.log('setting',value); } }; classInstance.prop=10;//logs:"setting",10 console.log(classInstance.prop);//logs:undefined Ifyouonlydefineagetter,attemptingtoassignthepropertywillhavenoeffect. constclassInstance=newclass{ getprop(){ return5; } }; classInstance.prop=10; console.log(classInstance.prop);//logs:5 PDF-DownloadJavaScriptforfree Previous Next ThismodifiedtextisanextractoftheoriginalStackOverflowDocumentationcreatedbyfollowingcontributorsandreleasedunderCCBY-SA3.0 ThiswebsiteisnotaffiliatedwithStackOverflow SUPPORT&PARTNERS Advertisewithus Contactus PrivacyPolicy STAYCONNECTED Getmonthlyupdatesaboutnewarticles,cheatsheets,andtricks.  Subscribe



請為這篇文章評分?