getter - JavaScript - MDN Web Docs

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

最少要有零個參數(請參見Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments 的詳細資料) ... SkiptomaincontentSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript參考文件FunctionsgetterArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.Tryit語法敘述示例規範瀏覽器相容性參見RelatedTopics JavaScript Tutorials: Completebeginners JavaScriptbasics JavaScriptfirststeps JavaScriptbuildingblocks IntroducingJavaScriptobjects JavaScriptGuide Introduction Grammarandtypes Controlflowanderrorhandling Loopsanditeration Functions Expressionsandoperators Numbersanddates Textformatting Regularexpressions Indexedcollections Keyedcollections Workingwithobjects Detailsoftheobjectmodel Usingpromises Iteratorsandgenerators Metaprogramming JavaScriptmodules Intermediate Client-sideJavaScriptframeworks Client-sidewebAPIs Are-introductiontoJavaScript JavaScriptdatastructures Equalitycomparisonsandsameness Closures Advanced Inheritanceandtheprototypechain Strictmode JavaScripttypedarrays MemoryManagement ConcurrencymodelandEventLoop References: Built-inobjects AggregateErrorArrayArrayBufferAsyncFunctionAtomicsBigIntBigInt64ArrayBigUint64ArrayBooleanDataViewDatedecodeURI()decodeURIComponent()encodeURI()encodeURIComponent()Error escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8ArrayInternalErrorIntlisFinite()isNaN()JSONMapMathNaNnullNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined unescape() uneval()URIErrorWeakMapWeakRefWeakSetWebAssembly Expressions&operators Additionassignment(+=)Addition(+)Assignment(=)asyncfunctionexpressionawaitBitwiseANDassignment(&=)BitwiseAND(&)BitwiseNOT(~)BitwiseORassignment(|=)BitwiseOR(|)BitwiseXORassignment(^=)BitwiseXOR(^)classexpressionCommaoperator(,)Conditional(ternary)operatorDecrement(--)deleteoperatorDestructuringassignmentDivisionassignment(/=)Division(/)Equality(==)Exponentiationassignment(**=)Exponentiation(**)function*expressionFunctionexpressionGreaterthanorequal(>=)Greaterthan(>)Groupingoperator()inoperatorIncrement(++)Inequality(!=)instanceofLeftshiftassignment(<<=)Leftshift(<>=)Rightshift(>>)Spreadsyntax(...)Strictequality(===)Strictinequality(!==)Subtractionassignment(-=)Subtraction(-)superthistypeofUnarynegation(-)Unaryplus(+)Unsignedrightshiftassignment(>>>=)Unsignedrightshift(>>>)voidoperatoryield*yield Statements&declarations asyncfunctionblockbreakclassconstcontinuedebuggerdo...whileemptyexportforawait...offor...infor...offorfunction*functiondeclarationif...elseimport.metaimportlabelletreturnswitchthrowtry...catchvarwhile with Functions TheargumentsobjectArrowfunctionexpressionsDefaultparametersgetterMethoddefinitionsRestparameterssetter Classes ClassstaticinitializationblocksconstructorextendsPrivateclassfeaturesPublicclassfieldsstatic Errors Warning:-file-isbeingassigneda//#sourceMappingURL,butalreadyhasoneTypeError:invalidArray.prototype.sortargumentWarning:08/09isnotalegalECMA-262octalconstantRangeError:radixmustbeanintegerSyntaxError:invalidregularexpressionflag"x"SyntaxError:returnnotinfunctionTypeError:X.prototype.ycalledonincompatibletypeReferenceError:can'taccesslexicaldeclaration`X'beforeinitializationTypeError:can'taccessproperty"x"of"y"TypeError:can'tassigntoproperty"x"on"y":notanobjectTypeError:can'tdefineproperty"x":"obj"isnotextensibleTypeError:property"x"isnon-configurableandcan'tbedeletedTypeError:can'tredefinenon-configurableproperty"x"TypeError: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:invalidarraylengthReferenceError:invalidassignmentleft-handsideTypeError: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:unterminatedstringliteral Misc JavaScripttechnologiesoverview Lexicalgrammar JavaScriptdatastructures Enumerabilityandownershipofproperties Iterationprotocols Strictmode Transitioningtostrictmode Templateliterals Deprecatedfeatures Tryit語法敘述示例規範瀏覽器相容性參見getterTryit get語法會將物件屬性,綁定到屬性被檢索時,所呼叫的函式。

語法{getprop(){...}} {get[expression](){...}}參數 prop 要綁定到給定函式的名稱。

expression 自ECMAScript2015開始,可以用計算屬性名稱(computedpropertyname),綁定到給定函式。

敘述有時候,物件的屬性可能需要回傳動態數值、或要在不使用明確的方法呼叫下,反映出內部變數的狀態。

在JavaScript可以用getter達到這個目的。

儘管可以用getter與setter的關聯建立虛擬屬性的類型,但getter無法被綁定到同時擁有實際數值的屬性。

使用get語法時,請注意以下情況: 可以擁有一個以數字或字串為代表的標示符; 最少要有零個參數(請參見IncompatibleES5change:literalgetterandsetterfunctionsmustnowhaveexactlyzerooronearguments的詳細資料) 不能以有另一個get的objectliteral、或相同屬性入口(dataentry)的data形式出現(不能使用{getx(){},getx(){}}and{x:...,getx(){}})。

getter可以用delete(en-US)操作符移除。

示例在物件初始器(objectinitializers)內定義新物件的getter這程式碼將給obj物件建立虛擬屬性latest,它會回傳log陣列的最後一個單元。

varobj={ log:['example','test'], getlatest(){ if(this.log.length==0)returnundefined; returnthis.log[this.log.length-1]; } } console.log(obj.latest);//"test". 請注意latest不會因為數值被指派而改變。

使用delete操作符移除getter如果想移除getter,可以使用delete(en-US)完成之: deleteobj.latest; 使用defineProperty給現有物件定義getter若想在任何時候給現有物件添增getter,請使用Object.defineProperty()。

varo={a:0}; Object.defineProperty(o,'b',{get:function(){returnthis.a+1;}}); console.log(o.b)//Runsthegetter,whichyieldsa+1(whichis1)使用計算屬性名varexpr='foo'; varobj={ get[expr](){return'bar';} }; console.log(obj.foo);//"bar"Smart/self-overwriting/lazygettersGetter提供了定義物件屬性的方法,但它本身並不會去自動計算,直到想訪問它。

除非需要用getter,否則數值計算會被延緩;如果不需要用到getter,那就永遠無須支付計算的開銷。

針對屬性值lazy或delay、並暫存以留作未來訪問的最佳化技巧稱作smart或memoizedgetter:初次計算時會呼叫getter、接著被暫存以便在不重算的情況下做後續訪問。

這種技巧在以下情況會派上用場: 如果數值開銷很昂貴(例如需要大量RAM或CPU時間、產生worker執行緒、檢索遠端文件等) 如果現在並不需要數值:可能是現在用不到、或在某些情況下完全用不到。

如果使用的話,該數值會被訪問數次、且該數值永遠不會更改、或不應該更改。

也就是說,出於getter不會重新計算的理由,不要針對數值預期會改變的屬性,使用lazygetter。

下例的物件擁有作為自己的屬性的getter。

在取得該屬性後,它會從物件被移除、並以隱式數值屬性重新增加、最後回傳之。

getnotifier(){ deletethis.notifier; returnthis.notifier=document.getElementById('bookmarked-notification-anchor'); }, 針對Firefox程式碼,另請參見定義defineLazyGetter()函式的XPCOMUtils.jsm程式模塊。

get與defineProperty在使用classes時,儘管get關鍵字與Object.defineProperty()會出現相同結果,但其中有微妙的差異。

在使用get時,屬性會在物件的原型被定義;而在使用Object.defineProperty()時,屬性會在被套用的實例內定義。

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}規範 規範 狀態 註解 ECMAScript5.1(ECMA-262)Thedefinitionof'ObjectInitializer'inthatspecification. Standard 初始定義。

ECMAScript2015(6thEdition,ECMA-262)Thedefinitionof'Methoddefinitions'inthatspecification. Standard 增加計算屬性名。

ECMAScript(ECMA-262)Thedefinitionof'Methoddefinitions'inthatspecification. LivingStandard   瀏覽器相容性BCDtablesonlyloadinthebrowser參見 setter delete(en-US) Object.defineProperty() __defineGetter__(en-US) __defineSetter__(en-US) JavaScript教學的定義Getter與Setter Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Dec8,2020,byMDNcontributors



請為這篇文章評分?