建構子- JavaScript - MDN Web Docs
文章推薦指數: 80 %
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
延伸文章資訊
- 1JavaScript Class Fundamentals: Introduction to ES6 Class
In the Person class, the constructor() is where you can initialize the properties of an instance....
- 2JavaScript Class constructor Method - W3Schools
The constructor() method is called automatically when a class is initiated, and it has to have th...
- 3Classes - JavaScript - MDN Web Docs
class Polygon { constructor(height, width) { this.height = height; this.width = width; } // Gette...
- 4JavaScript Class (類別) - Shubo 的程式開發筆記
如果要建構新物件,傳統的Prototype-based的寫法會需要:. 定義constructor; 在 prototype 物件上定義方法. function User(name) ...
- 5[JS]類別(class) - constructor、extends、super、static - HackMD
[JS]類別(class) - constructor、extends、super、static、Getter & Setter [JavaScript | ES6 中最容易誤會的語法糖 C.