JavaScript Tutorial => Getters and Setters
文章推薦指數: 80 %
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
延伸文章資訊
- 1JavaScript ES6 Class Syntax - Cory Rylan
ES6 classes brings a new syntax for getters and setters on object properties Get and set allows u...
- 2[JS] Getter and Setter 筆記 - pcwu's TIL Notes
JavaScript. 在JavaScript 中如果Class 在取屬性值或設定屬性值時,如果有比較複雜的運用時,可以使用 Getter 和 Setter 。
- 3getters and setters in JavaScript classes? - Tutorialspoint
Classes allow using getters and setters. It is smart to use getters and setters for the propertie...
- 4JavaScript Tutorial => Getters and Setters
In a class definition, a getter is written like a no-argument method prefixed by the get keyword....
- 5getter - JavaScript - MDN Web Docs
儘管可以用getter 與setter 的關聯建立虛擬屬性的類型,但getter 無法被綁 ... class Example { get hello() { return 'world'; }...