getter - JavaScript - MDN Web Docs
文章推薦指數: 80 %
Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers ... SkiptomaincontentSkiptosearchSkiptoselectlanguageReferencesJavaScriptJavaScriptFunctionsgetterArticleActionsEnglish(US)TryitSyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoRelatedTopics JavaScript Tutorials: Completebeginners JavaScriptbasics JavaScriptfirststeps JavaScriptbuildingblocks IntroducingJavaScriptobjects JavaScriptGuide Introduction Grammarandtypes Controlflowanderrorhandling Loopsanditeration Functions Expressionsandoperators Numbersanddates Textformatting Regularexpressions Indexedcollections Keyedcollections Workingwithobjects Usingclasses Usingpromises Iteratorsandgenerators Metaprogramming JavaScriptmodules Intermediate Client-sideJavaScriptframeworks Client-sidewebAPIs Languageoverview JavaScriptdatastructures Equalitycomparisonsandsameness Closures Advanced Inheritanceandtheprototypechain Strictmode JavaScripttypedarrays MemoryManagement ConcurrencymodelandEventLoop References: Built-inobjects OverviewAggregateErrorArrayArrayBufferAsyncFunctionAsyncGeneratorAsyncGeneratorFunctionAtomicsBigIntBigInt64ArrayBigUint64ArrayBooleanDataViewDatedecodeURI()decodeURIComponent()encodeURI()encodeURIComponent()Error Deprecated escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8Array Non-standard InternalErrorIntlisFinite()isNaN()JSONMapMathNaNNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined Deprecated unescape()URIErrorWeakMapWeakRefWeakSet Expressions&operators OverviewAddition(+)Additionassignment(+=)Assignment(=)asyncfunctionexpressionasyncfunction*expressionawaitBitwiseAND(&)BitwiseANDassignment(&=)BitwiseNOT(~)BitwiseOR(|)BitwiseORassignment(|=)BitwiseXOR(^)BitwiseXORassignment(^=)classexpressionCommaoperator(,)Conditional(ternary)operatorDecrement(--)deleteoperatorDestructuringassignmentDivision(/)Divisionassignment(/=)Equality(==)Exponentiation(**)Exponentiationassignment(**=)Functionexpressionfunction*expressionGreaterthan(>)Greaterthanorequal(>=)Groupingoperator()importimport.metainoperatorIncrement(++)Inequality(!=)instanceofLeftshift(<>)Rightshiftassignment(>>=)Spreadsyntax(...)Strictequality(===)Strictinequality(!==)Subtraction(-)Subtractionassignment(-=)superthistypeofUnarynegation(-)Unaryplus(+)Unsignedrightshift(>>>)Unsignedrightshiftassignment(>>>=)voidoperatoryieldyield* Statements&declarations Overviewasyncfunctionasyncfunction*blockbreakclassconstcontinuedebuggerdo...whileemptyexportforforawait...offor...infor...offunctiondeclarationfunction*if...elseimportlabelletreturnswitchthrowtry...catchvarwhile Deprecated with Functions OverviewTheargumentsobjectArrowfunctionexpressionsDefaultparametersgetterMethoddefinitionsRestparameterssetter Classes OverviewClassstaticinitializationblocksconstructorextendsPrivateclassfeaturesPublicclassfieldsstatic Errors OverviewWarning:-file-isbeingassigneda//#sourceMappingURL,butalreadyhasoneTypeError:invalidArray.prototype.sortargumentWarning:08/09isnotalegalECMA-262octalconstantRangeError:radixmustbeanintegerSyntaxError:invalidregularexpressionflag"x"SyntaxError:returnnotinfunctionRangeError:BigIntdivisionbyzeroRangeError:BigIntnegativeexponentTypeError:X.prototype.ycalledonincompatibletypeReferenceError:can'taccesslexicaldeclaration'X'beforeinitializationTypeError:can'tassigntoproperty"x"on"y":notanobjectRangeError:xcan'tbeconvertedtoBigIntbecauseitisn'tanintegerTypeError:can'tconvertBigInttonumberTypeError:can'tconvertxtoBigIntTypeError:can'tdefineproperty"x":"obj"isnotextensibleTypeError:property"x"isnon-configurableandcan'tbedeletedTypeError:can'tredefinenon-configurableproperty"x"SyntaxError:cannotuse`??`unparenthesizedwithin`||`and`&&`expressionsTypeError:cyclicobjectvalueTypeError:can'taccessdeadobjectSyntaxError:applyingthe'delete'operatortoanunqualifiednameisdeprecatedReferenceError:deprecatedcallerorargumentsusageWarning:expressionclosuresaredeprecatedSyntaxError:"0"-prefixedoctalliteralsandoctalescapeseq.aredeprecatedSyntaxError:Using//@toindicatesourceURLpragmasisdeprecated.Use//#insteadWarning:String.xisdeprecated;useString.prototype.xinsteadWarning:Date.prototype.toLocaleFormatisdeprecatedSyntaxError:testforequality(==)mistypedasassignment(=)?TypeError:settinggetter-onlyproperty"x"SyntaxError:Unexpected'#'usedoutsideofclassbodySyntaxError:identifierstartsimmediatelyafternumericliteralSyntaxError:illegalcharacterTypeError:cannotuse'in'operatortosearchfor'x'in'y'RangeError:invalidarraylengthSyntaxError:invalidassignmentleft-handsideSyntaxError:invalidBigIntsyntaxTypeError:invalidassignmenttoconst"x"RangeError:invaliddateSyntaxError:for-inloopheaddeclarationsmaynothaveinitializersSyntaxError:adeclarationintheheadofafor-ofloopcan'thaveaninitializerTypeError:invalid'instanceof'operand'x'TypeError:'x'isnotiterableSyntaxError:JSON.parse:badparsingSyntaxError:MalformedformalparameterURIError:malformedURIsequenceSyntaxError:missing]afterelementlistSyntaxError:missing:afterpropertyidSyntaxError:missing}afterfunctionbodySyntaxError:missing}afterpropertylistSyntaxError:missingformalparameterSyntaxError:missing=inconstdeclarationSyntaxError:missingnameafter.operatorSyntaxError:missing)afterargumentlistSyntaxError:missing)afterconditionSyntaxError:missing;beforestatementTypeError:MoreargumentsneededRangeError:repeatcountmustbenon-negativeTypeError:"x"isnotanon-nullobjectTypeError:"x"hasnopropertiesSyntaxError:missingvariablenameTypeError:can'tdeletenon-configurablearrayelementRangeError:argumentisnotavalidcodepointTypeError:"x"isnotaconstructorTypeError:"x"isnotafunctionReferenceError:"x"isnotdefinedRangeError:precisionisoutofrangeError:Permissiondeniedtoaccessproperty"x"TypeError:"x"isread-onlySyntaxError:redeclarationofformalparameter"x"TypeError:ReduceofemptyarraywithnoinitialvalueSyntaxError:"x"isareservedidentifierRangeError:repeatcountmustbelessthaninfinityWarning:unreachablecodeafterreturnstatementSyntaxError:"usestrict"notallowedinfunctionwithnon-simpleparametersInternalError:toomuchrecursionReferenceError:assignmenttoundeclaredvariable"x"ReferenceError:referencetoundefinedproperty"x"SyntaxError:UnexpectedtokenTypeError:"x"is(not)"y"SyntaxError:functionstatementrequiresanameSyntaxError:unparenthesizedunaryexpressioncan'tappearontheleft-handsideof'**'SyntaxError:unterminatedstringliteral Misc JavaScripttechnologiesoverview Lexicalgrammar JavaScriptdatastructures Enumerabilityandownershipofproperties Iterationprotocols Strictmode Transitioningtostrictmode Templateliterals Trailingcommas Deprecatedfeatures TryitSyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsogetter Thegetsyntaxbindsanobjectpropertytoafunction thatwillbecalledwhenthatpropertyislookedup. TryitSyntax{getprop(){/*…*/}} {get[expression](){/*…*/}} Parameters prop Thenameofthepropertytobindtothegivenfunction. expression Youcanalsouseexpressionsforacomputedpropertynametobindtothegivenfunction. Description Sometimesitisdesirabletoallowaccesstoapropertythatreturnsadynamically computedvalue,oryoumaywanttoreflectthestatusofaninternalvariablewithout requiringtheuseofexplicitmethodcalls.InJavaScript,thiscanbeaccomplishedwith theuseofagetter. Itisnotpossibletosimultaneouslyhaveagetterboundtoapropertyandhavethat propertyactuallyholdavalue,althoughitispossibletouseagetteranda setterinconjunctiontocreateatypeofpseudo-property. Notethefollowingwhenworkingwiththegetsyntax: Itcanhaveanidentifierwhichiseitheranumberorastring; Itmusthaveexactlyzeroparameters (seeIncompatibleES5change:literalgetterandsetterfunctionsmustnowhaveexactlyzerooronearguments formoreinformation); Itmustnotappearinanobjectliteralwithanothergete.g.thefollowingisforbidden { getx(){},getx(){} } Itmustnotappearwithadataentryforthesamepropertye.g.thefollowingisforbidden { x:/*…*/,getx(){/*…*/} } ExamplesDefiningagetteronnewobjectsinobjectinitializers Thiswillcreateapseudo-propertylatestforobjectobj, whichwillreturnthelastarrayiteminlog. constobj={ log:['example','test'], getlatest(){ if(this.log.length===0)returnundefined; returnthis.log[this.log.length-1]; } } console.log(obj.latest);//"test" Notethatattemptingtoassignavaluetolatestwillnotchangeit.Deletingagetterusingthedeleteoperator Ifyouwanttoremovethegetter,youcanjustdelete it: deleteobj.latest; DefiningagetteronexistingobjectsusingdefineProperty Toappendagettertoanexistingobjectlateratanytime,use Object.defineProperty(). consto={a:0}; Object.defineProperty(o,'b',{get(){returnthis.a+1;}}); console.log(o.b)//Runsthegetter,whichyieldsa+1(whichis1) Usingacomputedpropertynameconstexpr='foo'; constobj={ get[expr](){return'bar';} }; console.log(obj.foo);//"bar" DefiningstaticgettersclassMyConstants{ staticgetfoo(){ return'foo'; } } console.log(MyConstants.foo);//'foo' MyConstants.foo='bar'; console.log(MyConstants.foo);//'foo',astaticgetter'svaluecannotbechanged Smart/self-overwriting/lazygetters Gettersgiveyouawaytodefineapropertyofanobject,buttheydonot calculatetheproperty'svalueuntilitisaccessed.Agetterdefersthecost ofcalculatingthevalueuntilthevalueisneeded.Ifitisneverneeded,youneverpay thecost. Anadditionaloptimizationtechniquetolazifyordelaythecalculationofaproperty valueandcacheitforlateraccessaresmart(ormemoized)getters. Thevalueiscalculatedthefirsttimethegetteriscalled,andisthencachedso subsequentaccessesreturnthecachedvaluewithoutrecalculatingit.Thisisusefulin thefollowingsituations: Ifthecalculationofapropertyvalueisexpensive(takesmuchRAMorCPUtime, spawnsworkerthreads,retrievesremotefile,etc.). Ifthevalueisn'tneededjustnow.Itwillbeusedlater,orinsomecaseit'snot usedatall. Ifit'sused,itwillbeaccessedseveraltimes,andthereisnoneedto re-calculatethatvaluewillneverbechangedorshouldn'tbere-calculated. Note:Thismeansthatyoushouldn'twritealazygetterforapropertywhosevalueyou expecttochange,becauseifthegetterislazythenitwillnotrecalculatethe value. Notethatgettersarenot"lazy"or"memoized"bynature;youmustimplementthis techniqueifyoudesirethisbehavior. Inthefollowingexample,theobjecthasagetterasitsownproperty.Ongettingthe property,thepropertyisremovedfromtheobjectandre-added,butimplicitlyasadata propertythistime.Finally,thevaluegetsreturned. constobj={ getnotifier(){ deletethis.notifier; returnthis.notifier=document.getElementById('bookmarked-notification-anchor'); }, } getvs.defineProperty WhileusingthegetkeywordandObject.defineProperty()have similarresults,thereisasubtledifferencebetweenthetwowhenusedon classes. Whenusinggetthepropertywillbedefinedontheinstance'sprototype, whileusingObject.defineProperty()thepropertywillbedefinedonthe instanceitisappliedto. classExample{ gethello(){ return'world'; } } constobj=newExample(); console.log(obj.hello); //"world" console.log(Object.getOwnPropertyDescriptor(obj,'hello')); //undefined console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(obj),'hello' ) ); //{configurable:true,enumerable:false,get:functiongethello(){return'world';},set:undefined} SpecificationsSpecificationECMAScriptLanguageSpecification#sec-method-definitionsBrowsercompatibilityBCDtablesonlyloadinthebrowserSeealso Setter delete Object.defineProperty() Object.prototype.__defineGetter__() Object.prototype.__defineSetter__() DefininggettersandsettersinJavaScriptGuide Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Sep13,2022,byMDNcontributors
延伸文章資訊
- 1JS Getter 與Setter DAY71 - iT 邦幫忙
Setter 與Setter Getter: 取得特定值的方法. Setter: 存值的方法. Getter var wallet = { total: 100, set save(price)...
- 2JavaScript - 屬性描述器(2) - iT 邦幫忙
I Want To Know JS 系列第32 篇 ... Getter. 取值器中,需要回傳一個值來當作取值的結果: ... 大致上來講,我們需要三個東西:. 取值器. getter. 設值器...
- 3属性的getter 和setter - 现代JavaScript 教程
访问器属性由“getter” 和“setter” 方法表示。在对象字面量中,它们用 get 和 set 表示:. let obj = { get propName() { // 当读取obj.
- 4JavaScript Getter and Setter (with Examples) - Programiz
In this tutorial, you will learn about JavaScript getter and setter methods with the help of exam...
- 5JavaScript Object Accessors - W3Schools
Getters and setters allow you to define Object Accessors (Computed Properties). JavaScript Getter...