JavaScript Getter and Setter (with Examples) - Programiz

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

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



請為這篇文章評分?