建構子- JavaScript - MDN Web Docs

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

constructor(建構子)是個隨著class 一同建立並初始化物件的特殊方法。

SkiptomaincontentSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript參考文件Classes建構子ArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity.語法敘述示例規範瀏覽器相容性參見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 語法敘述示例規範瀏覽器相容性參見建構子 constructor(建構子)是個隨著class一同建立並初始化物件的特殊方法。

語法constructor([arguments]){...}敘述一個class只能有一個稱為constructor的特殊物件。

如果一個class出現兩次以上的constructor,就會發生SyntaxError錯誤。

如果不指定建構子,就會使用預設的建構子。

示例使用constructor方法這段程式碼是從classessample擷取而來。

(線上範例) classSquareextendsPolygon{ constructor(length){ //我們在這裡呼叫了class的建構子提供多邊形的長寬值 super(length,length); //注意:在derivedclass中,super()必須在使用this以前被呼叫。

不這樣的話會發生錯誤。

this.name='Square'; } getarea(){ returnthis.height*this.width; } setarea(value){ this.area=value; } }預設的建構子如上文所說:如果不指定建構子,就會使用預設的建構子。

對baseclasses而言,預設的建構子長得像這樣: constructor(){} 對derivedclass而言,預設的建構子長得像這樣: constructor(...args){ super(...args); }規範SpecificationECMAScriptLanguageSpecification#sec-static-semantics-constructormethod瀏覽器相容性BCDtablesonlyloadinthebrowser參見 super() classexpression(en-US) classdeclaration(en-US) Classes Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Feb15,2022,byMDNcontributors



請為這篇文章評分?