JavaScript Class Getter/Setter - Stack Overflow

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

Javascript supports getters and setters. class Form{ set foo(val){ console.log("setting foo") this.fooValue = val; } get foo(){ ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore JavaScriptClassGetter/Setter AskQuestion Asked 3years,11monthsago Modified 3years,11monthsago Viewed 26ktimes 9 1 isthereawaytolistenforapropertycallonaJavaScriptClass forexamplewhenigosomethinglikethis: myForm=newForm(); myForm.name='Name'; ->whenisetthenameidontonlywanttosetthepropertybutialsowanttoupdatemyVuexstore. SamethingwithgetiwouldliketoreadfromVuexstore. IknoewtherearethinslikeProxybutforthisineedtowrapmyClasswithaProxyobject.Notsosureifilikethis. module.exports=newProxy(newForm({}),{ get(receiver,name){ console.log('gettingpropertyfromVuexStore'); } }); Whatineedissomethinglikethis: module.exports=classForm{ //thisshouldbetriggeredwhenform.something get(property){ returnthis[property]; } //thisshouldbetriggeredwhenfrom.something='something' set(property,value){ returnthis[property]=value; } }; itthereabestpracticeforthis? javascriptecmascript-6 Share Follow askedApr18,2018at8:43 therabbityouknowtherabbityouknow 19322goldbadges55silverbadges1515bronzebadges 4 1 PossibleduplicateofJavascriptgettersandsettersfordummies? – notgiorgi Apr18,2018at8:52 1 @notgiorgi,It'snotaduplicate.TheOPasksaboutsettinggettersandsettersforeveryproperty,eventhosethatarenotdefined. – StefanOctavian Apr18,2018at8:55 Don'tuseaproxywhenyouknowthenamesofyourgetters/settersbeforehand. – Bergi Apr18,2018at9:13 @StefanOctavianThat'snotclearfromthequestionatall? – Bergi Apr18,2018at9:13 Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 18 Javascriptsupportsgettersandsetters classForm{ setfoo(val){ console.log("settingfoo") this.fooValue=val; } getfoo(){ console.log("gettingfoo"); returnthis.fooValue; } } letfrm=newForm(); frm.foo="bar"; console.log(frm.foo); YoucouldmakethismoredynamicbywritingawithGetterSettermethodwhichwrapseachpropertyofanobjectwithagetter/setter. varform={ a:"aValue", b:"bValue" } functionwithGetterSetter(obj){ varkeys=Object.keys(obj); varresult={}; for(vari=0;i



請為這篇文章評分?