Public class fields - JavaScript - MDN Web Docs

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

Both static and instance public fields are writable, enumerable, and configurable properties. As such, unlike their private counterparts, they ... SkiptomaincontentSkiptoselectlanguageReferencesJavaScriptJavaScriptClassesPublicclassfieldsArticleActionsEnglish(US)SyntaxExamplesSpecificationsBrowsercompatibilitySeealsoRelatedTopics 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 SyntaxExamplesSpecificationsBrowsercompatibilitySeealsoPublicclassfields Bothstaticandinstancepublicfieldsarewritable,enumerable,andconfigurable properties.Assuch,unliketheirprivatecounterparts,theyparticipateinprototype inheritance. SyntaxclassClassWithInstanceField{ instanceField='instancefield' } classClassWithStaticField{ staticstaticField='staticfield' } classClassWithPublicInstanceMethod{ publicMethod(){ return'helloworld' } } ExamplesPublicstaticfields Publicstaticfieldsareusefulwhenyouwantafieldtoexistonlyonceperclass,not oneveryclassinstanceyoucreate.Thisisusefulforcaches,fixed-configuration,or anyotherdatayoudon'tneedtobereplicatedacrossinstances. Publicstaticfieldsaredeclaredusingthestatickeyword.Theyareadded totheclassconstructoratthetimeofclassevaluationusing Object.defineProperty().Theyare accessedagainfromtheclassconstructor. classClassWithStaticField{ staticstaticField='staticfield' } console.log(ClassWithStaticField.staticField) //expectedoutput:"staticfield" Fieldswithoutinitializersareinitializedtoundefined. classClassWithStaticField{ staticstaticField } console.assert(ClassWithStaticField.hasOwnProperty('staticField')) console.log(ClassWithStaticField.staticField) //expectedoutput:"undefined" Publicstaticfieldsarenotreinitializedonsubclasses,butcanbeaccessedviathe prototypechain. classClassWithStaticField{ staticbaseStaticField='basefield' } classSubClassWithStaticFieldextendsClassWithStaticField{ staticsubStaticField='subclassfield' } console.log(SubClassWithStaticField.subStaticField) //expectedoutput:"subclassfield" console.log(SubClassWithStaticField.baseStaticField) //expectedoutput:"basefield" Wheninitializingfields,thisreferstotheclassconstructor.Youcan alsoreferenceitbyname,andusesupertogetthesuperclassconstructor (ifoneexists). classClassWithStaticField{ staticbaseStaticField='basestaticfield' staticanotherBaseStaticField=this.baseStaticField staticbaseStaticMethod(){return'basestaticmethodoutput'} } classSubClassWithStaticFieldextendsClassWithStaticField{ staticsubStaticField=super.baseStaticMethod() } console.log(ClassWithStaticField.anotherBaseStaticField) //expectedoutput:"basestaticfield" console.log(SubClassWithStaticField.subStaticField) //expectedoutput:"basestaticmethodoutput" Publicinstancefields Publicinstancefieldsexistoneverycreatedinstanceofaclass.Bydeclaringa publicfield,youcanensurethefieldisalwayspresent,andtheclassdefinitionis moreself-documenting. PublicinstancefieldsareaddedwithObject.defineProperty()eitheratconstructiontimeinthebaseclass(beforethe constructorbodyruns),orjustaftersuper()returnsinasubclass. classClassWithInstanceField{ instanceField='instancefield' } constinstance=newClassWithInstanceField() console.log(instance.instanceField) //expectedoutput:"instancefield" Fieldswithoutinitializersareinitializedtoundefined. classClassWithInstanceField{ instanceField } constinstance=newClassWithInstanceField() console.assert(instance.hasOwnProperty('instanceField')) console.log(instance.instanceField) //expectedoutput:"undefined" Likeproperties,fieldnamesmaybecomputed. constPREFIX='prefix' classClassWithComputedFieldName{ [`${PREFIX}Field`]='prefixedfield' } constinstance=newClassWithComputedFieldName() console.log(instance.prefixField) //expectedoutput:"prefixedfield" Wheninitializingfieldsthisreferstotheclassinstanceunder construction.Justasinpublicinstancemethods,ifyou'reinasubclassyoucanaccess thesuperclassprototypeusingsuper. classClassWithInstanceField{ baseInstanceField='basefield' anotherBaseInstanceField=this.baseInstanceField baseInstanceMethod(){return'basemethodoutput'} } classSubClassWithInstanceFieldextendsClassWithInstanceField{ subInstanceField=super.baseInstanceMethod() } constbase=newClassWithInstanceField() constsub=newSubClassWithInstanceField() console.log(base.anotherBaseInstanceField) //expectedoutput:"basefield" console.log(sub.subInstanceField) //expectedoutput:"basemethodoutput" PublicmethodsPublicstaticmethods Thestatickeyworddefinesastaticmethodforaclass. Staticmethodsaren'tcalledoninstancesoftheclass.Instead,they'recalledonthe classitself.Theseareoftenutilityfunctions,suchasfunctionstocreateorclone objects. classClassWithStaticMethod{ staticstaticMethod(){ return'staticmethodhasbeencalled.'; } } console.log(ClassWithStaticMethod.staticMethod()); //expectedoutput:"staticmethodhasbeencalled." Thestaticmethodsareaddedtotheclassconstructorwith Object.defineProperty()atclass evaluationtime.Thesemethodsarewritable,non-enumerable,andconfigurable. Publicinstancemethods Asthenameimplies,publicinstancemethodsaremethodsavailableonclassinstances. classClassWithPublicInstanceMethod{ publicMethod(){ return'helloworld' } } constinstance=newClassWithPublicInstanceMethod() console.log(instance.publicMethod()) //expectedoutput:"helloworld" Publicinstancemethodsareaddedtotheclassprototypeatthetimeofclass evaluationusingObject.defineProperty().Theyarewritable,non-enumerable,andconfigurable. Youmaymakeuseofgenerator,async,andasyncgeneratorfunctions. classClassWithFancyMethods{ *generatorMethod(){} asyncasyncMethod(){} async*asyncGeneratorMethod(){} } Insideinstancemethods,thisreferstotheinstanceitself.In subclasses,superletsyouaccessthesuperclassprototype,allowingyouto callmethodsfromthesuperclass. classBaseClass{ msg='helloworld' basePublicMethod(){ returnthis.msg } } classSubClassextendsBaseClass{ subPublicMethod(){ returnsuper.basePublicMethod() } } constinstance=newSubClass() console.log(instance.subPublicMethod()) //expectedoutput:"helloworld" Gettersandsettersarespecialmethodsthatbindtoaclasspropertyandarecalled whenthatpropertyisaccessedorset.Usethegetandsetsyntaxtodeclarea publicinstancegetterorsetter. classClassWithGetSet{ #msg='helloworld' getmsg(){ returnthis.#msg } setmsg(x){ this.#msg=`hello${x}` } } constinstance=newClassWithGetSet() console.log(instance.msg) //expectedoutput:"helloworld" instance.msg='cake' console.log(instance.msg) //expectedoutput:"hellocake" SpecificationsSpecificationECMAScriptLanguageSpecification#prod-FieldDefinitionBrowsercompatibilityBCDtablesonlyloadinthebrowserSeealso The SemanticsofAllJSClassElements Publicandprivateclassfields articleatthev8.devsite Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Jan20,2022,byMDNcontributors



請為這篇文章評分?