JavaScript Getter and Setter (with Examples) - Programiz
文章推薦指數: 80 %
JavaScript Getter and Setter ; Data properties; Accessor properties ; get - to define a getter method to get the property value; set - to define a setter method ... CourseIndex ExploreProgramiz Python JavaScript C C++ Java Kotlin Swift C# DSA StartLearningJavaScript ExploreJavaScriptExamples PopularTutorials OperatorsinJavaScript JavaScriptforLoop FunctionsinJavaScript JavaScriptObjects ArraysinJavaScript PopularExamples JavaScript"HelloWorld"Program Calculatetheareaofatriangle Checkifanumberisoddoreven FindtheGCD PrinttheFibonacciseries ReferenceMaterials StringMethods ArrayMethods MathObject Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster ViewallCourses Python JavaScript C C++ Java Kotlin Swift C# DSA StartLearning JavaScript PopularTutorials OperatorsinJavaScript JavaScriptforLoop FunctionsinJavaScript JavaScriptObjects ArraysinJavaScript Viewalltutorials ReferenceMaterials StringMethods ArrayMethods MathObject Viewall Python JavaScript C C++ Java Kotlin ExploreJavaScriptExamples PopularExamples JavaScript"HelloWorld"Program Calculatetheareaofatriangle Checkifanumberisoddoreven FindtheGCD PrinttheFibonacciseries Viewallexamples 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.chageName='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
ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Ob...
- 2setter - JavaScript - MDN Web Docs
最少要有一個參數(請參見Incompatible ES5 change: literal getter and setter functions must now have exactly ze...
- 3JS Getter 與Setter DAY71 - iT 邦幫忙::一起幫忙解決難題
Setter 與Setter Getter: 取得特定值的方法Setter: 存值的方法Getter var wallet = { total: 100, set save(price){ th...
- 4getter - JavaScript - MDN Web Docs
最少要有零個參數(請參見Incompatible ES5 change: literal getter and setter functions must now have exactly ze...
- 57天搞懂JS進階議題(day05)-getter & setter: 屬性描述器
7天搞懂JS進階議題(day05)-getter & setter: 屬性描述器. February 27, 2020. 本系列文章討論JS 物件導向設計相關的特性。 不含CSS,不含HTML!...