JavaScript Object Accessors - W3Schools
文章推薦指數: 80 %
Getters and setters allow you to define Object Accessors (Computed Properties). JavaScript Getter (The get Keyword). This example uses a lang property to get ... Tutorials References Exercises Videos Menu Login FreeWebsite GetCertified Pro HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOWTO W3.CSS C C++ C# REACT R JQUERY DJANGO TYPESCRIPT NODEJS MYSQL Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility Blog DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises PythonExercises SQLExercises PHPExercises JavaExercises CExercises C++Exercises C#Exercises jQueryExercises React.jsExercises MySQLExercises Bootstrap5Exercises Bootstrap4Exercises Bootstrap3Exercises NumPyExercises PandasExercises SciPyExercises TypeScriptExercises ExcelExercises RExercises GitExercises KotlinExercises GoExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz PythonQuiz SQLQuiz PHPQuiz JavaQuiz CQuiz C++Quiz C#Quiz jQueryQuiz React.jsQuiz MySQLQuiz Bootstrap5Quiz Bootstrap4Quiz Bootstrap3Quiz NumPyQuiz PandasQuiz SciPyQuiz TypeScriptQuiz XMLQuiz RQuiz GitQuiz KotlinQuiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse PythonCourse SQLCourse PHPCourse JavaCourse C++Course C#Course jQueryCourse React.jsCourse Bootstrap4Course Bootstrap3Course NumPyCourse PandasCourse TypeScriptCourse XMLCourse RCourse DataAnalyticsCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate PythonCertificate SQLCertificate PHPCertificate JavaCertificate C++Certificate C#Certificate jQueryCertificate React.jsCertificate MySQLCertificate Bootstrap5Certificate Bootstrap4Certificate Bootstrap3Certificate TypeScriptCertificate XMLCertificate ExcelCertificate DataScienceCertificate CyberSecurityCertificate AccessibilityCertificate × Tutorials References Exercises GetCertified Spaces Videos Shop Pro JSTutorial JSHOME JSIntroduction JSWhereTo JSOutput JSStatements JSSyntax JSComments JSVariables JSLet JSConst JSOperators JSArithmetic JSAssignment JSPrecedence JSDataTypes JSFunctions JSObjects JSEvents JSStrings JSStringMethods JSStringSearch JSStringTemplates JSNumbers JSNumberMethods JSArrays JSArrayMethods JSArraySort JSArrayIteration JSArrayConst JSDates JSDateFormats JSDateGetMethods JSDateSetMethods JSMath JSRandom JSBooleans JSComparisons JSIfElse JSSwitch JSLoopFor JSLoopForIn JSLoopForOf JSLoopWhile JSBreak JSIterables JSSets JSMaps JSTypeof JSTypeConversion JSBitwise JSRegExp JSErrors JSScope JSHoisting JSStrictMode JSthisKeyword JSArrowFunction JSClasses JSModules JSJSON JSDebugging JSStyleGuide JSBestPractices JSMistakes JSPerformance JSReservedWords JSVersions JSVersions JS2009(ES5) JS2015(ES6) JS2016 JS2017 JS2018 JS2019/2020 JSIE/Edge JSHistory JSObjects ObjectDefinitions ObjectProperties ObjectMethods ObjectDisplay ObjectAccessors ObjectConstructors ObjectPrototypes ObjectIterables ObjectSets ObjectMaps ObjectReference JSFunctions FunctionDefinitions FunctionParameters FunctionInvocation FunctionCall FunctionApply FunctionBind FunctionClosures JSClasses ClassIntro ClassInheritance ClassStatic JSAsync JSCallbacks JSAsynchronous JSPromises JSAsync/Await JSHTMLDOM DOMIntro DOMMethods DOMDocument DOMElements DOMHTML DOMForms DOMCSS DOMAnimations DOMEvents DOMEventListener DOMNavigation DOMNodes DOMCollections DOMNodeLists JSBrowserBOM JSWindow JSScreen JSLocation JSHistory JSNavigator JSPopupAlert JSTiming JSCookies JSWebAPIs WebAPIIntro WebFormsAPI WebHistoryAPI WebStorageAPI WebWorkerAPI WebFetchAPI WebGeolocationAPI JSAJAX AJAXIntro AJAXXMLHttp AJAXRequest AJAXResponse AJAXXMLFile AJAXPHP AJAXASP AJAXDatabase AJAXApplications AJAXExamples JSJSON JSONIntro JSONSyntax JSONvsXML JSONDataTypes JSONParse JSONStringify JSONObjects JSONArrays JSONServer JSONPHP JSONHTML JSONJSONP JSvsjQuery jQuerySelectors jQueryHTML jQueryCSS jQueryDOM JSGraphics JSGraphics JSCanvas JSPlotly JSChart.js JSGoogleChart JSD3.js JSExamples JSExamples JSHTMLDOM JSHTMLInput JSHTMLObjects JSHTMLEvents JSBrowser JSEditor JSExercises JSQuiz JSCertificate JSReferences JavaScriptObjects HTMLDOMObjects JavaScriptObjectAccessors ❮Previous Next❯ JavaScriptAccessors(GettersandSetters) ECMAScript5(ES52009)introducedGetterandSetters. GettersandsettersallowyoutodefineObjectAccessors(Computed Properties). JavaScriptGetter(ThegetKeyword) Thisexampleusesalangpropertytoget thevalueofthelanguageproperty. Example //Createanobject: constperson={ firstName:"John", lastName:"Doe", language:"en", getlang(){ returnthis.language; }}; //Displaydatafromtheobjectusingagetter: document.getElementById("demo").innerHTML=person.lang; TryitYourself» JavaScriptSetter(ThesetKeyword) Thisexampleusesalangpropertytoset thevalueofthelanguageproperty. Example constperson={ firstName:"John", lastName:"Doe", language:"", setlang(lang){ this.language=lang; }}; //Setanobject propertyusingasetter: person.lang="en"; //Displaydatafromtheobject: document.getElementById("demo").innerHTML=person.language; TryitYourself» JavaScriptFunctionorGetter? Whatisthedifferencesbetweenthesetwoexamples? Example1 constperson={ firstName:"John", lastName:"Doe", fullName:function(){ returnthis.firstName+""+ this.lastName; } };//Displaydatafromtheobjectusingamethod: document.getElementById("demo").innerHTML=person.fullName(); TryitYourself» Example2 constperson={ firstName:"John", lastName:"Doe", getfullName(){ returnthis.firstName+""+ this.lastName; } };//Displaydatafromtheobjectusingagetter: document.getElementById("demo").innerHTML=person.fullName; TryitYourself» Example1accessfullNameasafunction:person.fullName(). Example2accessfullNameasaproperty:person.fullName. Thesecondexampleprovidesasimplersyntax. DataQuality JavaScriptcansecurebetterdataqualitywhenusinggettersandsetters. Usingthelangproperty,inthisexample,returnsthevalue ofthelanguagepropertyinuppercase: Example //Createanobject: constperson={ firstName:"John", lastName:"Doe", language:"en", getlang(){ returnthis.language.toUpperCase(); }}; //Displaydatafromtheobjectusingagetter: document.getElementById("demo").innerHTML=person.lang; TryitYourself» Usingthelangproperty,inthisexample,storesanuppercase valueinthelanguageproperty: Example constperson={ firstName:"John", lastName:"Doe", language:"", setlang(lang){ this.language=lang.toUpperCase(); }}; //Setanobject propertyusingasetter: person.lang="en"; //Displaydatafromtheobject: document.getElementById("demo").innerHTML=person.language; TryitYourself» WhyUsingGettersandSetters? Itgivessimplersyntax Itallowsequalsyntaxforpropertiesandmethods Itcansecurebetterdataquality Itisusefulfordoingthingsbehind-the-scenes Object.defineProperty() TheObject.defineProperty()methodcanalsobeusedtoaddGettersand Setters: ACounterExample //Defineobject constobj={counter:0}; //Definesettersandgetters Object.defineProperty(obj,"reset",{ get:function(){this.counter=0;}}); Object.defineProperty(obj,"increment",{ get:function(){this.counter++;}}); Object.defineProperty(obj,"decrement",{ get:function(){this.counter--;}}); Object.defineProperty(obj,"add",{ set:function(value){this.counter+=value;}}); Object.defineProperty(obj,"subtract",{ set:function(value){this.counter-=value;}}); //Playwiththecounter: obj.reset; obj.add=5; obj.subtract=1; obj.increment; obj.decrement; TryitYourself» ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1属性的getter 和setter - 现代JavaScript 教程
访问器属性由“getter” 和“setter” 方法表示。在对象字面量中,它们用 get 和 set 表示:. let obj = { get propName() { // 当读取obj.
- 2JavaScript Object Accessors - W3Schools
Getters and setters allow you to define Object Accessors (Computed Properties). JavaScript Getter...
- 3[JS] Getter and Setter 筆記 - pcwu's TIL Notes
[JS] Getter and Setter 筆記. 12 Feb 2017. JavaScript. 在JavaScript 中如果Class 在取屬性值或設定屬性值時,如果有比較複雜的運用時...
- 4JS Getter 與Setter DAY71 - iT 邦幫忙
Setter 與Setter Getter: 取得特定值的方法. Setter: 存值的方法. Getter var wallet = { total: 100, set save(price)...
- 57天搞懂JS進階議題(day05)-getter & setter: 屬性描述器
本系列文章討論JS 物件導向設計相關的特性。 不含CSS,不含HTML! 建議先有些JS基礎再繼續閱讀。 你也可以看看從零開始遲來的Web開發筆記