JavaScript Getter and Setter (with Examples) - Programiz

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

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



請為這篇文章評分?