JavaScript Getter and Setter (with Examples) - Programiz
文章推薦指數: 80 %
In this tutorial, you will learn about JavaScript getter and setter methods with the help of examples. CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials OperatorsinJavaScript JavaScriptforLoop FunctionsinJavaScript JavaScriptObjects ArraysinJavaScript StartLearningJavaScript PopularExamples JavaScript"HelloWorld"Program Calculatetheareaofatriangle Checkifanumberisoddoreven FindtheGCD PrinttheFibonacciseries ExploreJavaScriptExamples ReferenceMaterials StringMethods ArrayMethods MathObject Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA PopularTutorials OperatorsinJavaScript JavaScriptforLoop FunctionsinJavaScript JavaScriptObjects ArraysinJavaScript StartLearningJavaScript AllJavaScriptTutorials ReferenceMaterials StringMethods ArrayMethods MathObject Viewall Python JavaScript C C++ Java Kotlin PopularExamples JavaScript"HelloWorld"Program Calculatetheareaofatriangle Checkifanumberisoddoreven FindtheGCD PrinttheFibonacciseries AllJavaScriptExamples JSIntroduction GettingStarted JSVariables&Constants JSconsole.log JavaScriptDatatypes JavaScriptOperators JavaScriptComments JSTypeConversions JSControlFlow JSComparisonOperators JavaScriptifelseStatement JavaScriptforloop JavaScriptwhileloop JavaScriptbreakStatement JavaScriptcontinueStatement JavaScriptswitchStatement JSFunctions JavaScriptFunction VariableScope JavaScriptHoisting JavaScriptRecursion JSObjects JavaScriptObjects JavaScriptMethods&this JavaScriptConstructor JavaScriptGetterandSetter JavaScriptPrototype JSTypes JavaScriptArray JSMultidimensionalArray JavaScriptString JavaScriptfor...inloop JavaScriptNumber JavaScriptSymbol ExceptionsandModules JavaScripttry...catch...finally JavaScriptthrowStatement JavaScriptModules JSES6 JavaScriptES6 JavaScriptArrowFunction JavaScriptDefaultParameters JavaScriptTemplateLiterals JavaScriptSpreadOperator JavaScriptMap JavaScriptSet DestructuringAssignment JavaScriptClasses JavaScriptInheritance JavaScriptfor...of JavaScriptProxies JavaScriptAsynchronous JavaScriptsetTimeout() JavaScriptCallBackFunction JavaScriptPromise Javascriptasync/await JavaScriptsetInterval() Miscellaneous JavaScriptJSON JavaScriptDateandTime JavaScriptClosure JavaScriptthis JavaScript'usestrict' IteratorsandIterables JavaScriptGenerators JavaScriptRegularExpressions JavaScriptBrowserDebugging UsesofJavaScript RelatedTopics JavascriptObject.defineProperty() JavaScriptObjects JavaScriptMethodsandthisKeyword JavaScriptClasses JavaScriptfor...inloop JavaScriptProxies JavaScriptGetterandSetter Inthistutorial,youwilllearnaboutJavaScriptgetterandsettermethodswiththehelpofexamples. InJavaScript,therearetwokindsofobjectproperties: Dataproperties Accessorproperties DataProperty Here'sanexampleofdatapropertythatwehavebeenusingintheprevioustutorials. conststudent={ //dataproperty firstName:'Monica'; }; AccessorProperty InJavaScript,accessorpropertiesaremethodsthatgetorsetthevalueofanobject.Forthat,weusethesetwokeywords: get-todefineagettermethodtogetthepropertyvalue set-todefineasettermethodtosetthepropertyvalue JavaScriptGetter InJavaScript,gettermethodsareusedtoaccessthepropertiesofanobject.Forexample, conststudent={ //dataproperty firstName:'Monica', //accessorproperty(getter) getgetName(){ returnthis.firstName; } }; //accessingdataproperty console.log(student.firstName);//Monica //accessinggettermethods console.log(student.getName);//Monica //tryingtoaccessasamethod console.log(student.getName());//error Intheaboveprogram,agettermethodgetName()iscreatedtoaccessthepropertyofanobject. getgetName(){ returnthis.firstName; } Note:Tocreateagettermethod,thegetkeywordisused. Andalsowhenaccessingthevalue,weaccessthevalueasaproperty. student.getName; Whenyoutrytoaccessthevalueasamethod,anerroroccurs. console.log(student.getName());//error JavaScriptSetter InJavaScript,settermethodsareusedtochangethevaluesofanobject.Forexample, conststudent={ firstName:'Monica', //accessorproperty(setter) setchangeName(newName){ this.firstName=newName; } }; console.log(student.firstName);//Monica //change(set)objectpropertyusingasetter student.changeName='Sarah'; console.log(student.firstName);//Sarah Intheaboveexample,thesettermethodisusedtochangethevalueofanobject. setchangeName(newName){ this.firstName=newName; } Note:Tocreateasettermethod,thesetkeywordisused. Asshownintheaboveprogram,thevalueoffirstNameisMonica. ThenthevalueischangedtoSarah. student.changeName='Sarah'; Note:Settermusthaveexactlyoneformalparameter. JavaScriptObject.defineProperty() InJavaScript,youcanalsouseObject.defineProperty()methodtoaddgettersandsetters.Forexample, conststudent={ firstName:'Monica' } //gettingproperty Object.defineProperty(student,"getName",{ get:function(){ returnthis.firstName; } }); //settingproperty Object.defineProperty(student,"changeName",{ set:function(value){ this.firstName=value; } }); console.log(student.firstName);//Monica //changingthepropertyvalue student.changeName='Sarah'; console.log(student.firstName);//Sarah Intheaboveexample,Object.defineProperty()isusedtoaccessandchangethepropertyofanobject. ThesyntaxforusingObject.defineProperty()is: Object.defineProperty(obj,prop,descriptor) TheObject.defineProperty()methodtakesthreearguments. ThefirstargumentistheobjectName. Thesecondargumentisthenameoftheproperty. Thethirdargumentisanobjectthatdescribestheproperty. TableofContents Introduction JavaScriptGetter JavaScriptSetter JavaScriptObject.defineProperty() PreviousTutorial: JSConstructorFunction NextTutorial: JSPrototype Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsJavaScriptTutorialJavaScriptObjectsJavaScriptTutorialJavaScriptMethodsandthisKeywordJavaScriptTutorialJavaScriptClassesJavaScriptTutorialJavaScriptfor...inloop
延伸文章資訊
- 1JavaScript Object Accessors - W3Schools
Getters and setters allow you to define Object Accessors (Computed Properties). JavaScript Getter...
- 2[JS] Getter and Setter 筆記 - pcwu's TIL Notes
[JS] Getter and Setter 筆記. 12 Feb 2017. JavaScript. 在JavaScript 中如果Class 在取屬性值或設定屬性值時,如果有比較複雜的運用時...
- 3JavaScript - 屬性描述器(2) - iT 邦幫忙
I Want To Know JS 系列第32 篇 ... Getter. 取值器中,需要回傳一個值來當作取值的結果: ... 大致上來講,我們需要三個東西:. 取值器. getter. 設值器...
- 4JavaScript Getter and Setter (with Examples) - Programiz
In this tutorial, you will learn about JavaScript getter and setter methods with the help of exam...
- 5JS Getter 與Setter DAY71 - iT 邦幫忙
Setter 與Setter Getter: 取得特定值的方法. Setter: 存值的方法. Getter var wallet = { total: 100, set save(price)...