物件的使用 - JavaScript - MDN Web Docs
文章推薦指數: 80 %
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) ...
SkiptomaincontentSkiptosearchSkiptoselectlanguage給開發者的網頁技術文件JavaScriptJavaScript指南物件的使用ArticleActions正體中文(繁體)ThispagewastranslatedfromEnglishbythecommunity.LearnmoreandjointheMDNWebDocscommunity."物件"概觀物件與屬性EnumeratethepropertiesofanobjectCreatingnewobjectsInheritanceIndexingobjectpropertiesDefiningpropertiesforanobjecttypeDefiningmethodsUsingthisforobjectreferencesDefininggettersandsettersDeletingpropertiesComparingObjectsSeealsoRelatedTopics
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
已棄用
escape()eval()EvalErrorFinalizationRegistryFloat32ArrayFloat64ArrayFunctionGeneratorGeneratorFunctionglobalThisInfinityInt16ArrayInt32ArrayInt8Array
非標準
InternalErrorIntlisFinite()isNaN()JSONMapMathNaNNumberObjectparseFloat()parseInt()PromiseProxyRangeErrorReferenceErrorReflectRegExpSetSharedArrayBufferStringSymbolSyntaxErrorTypedArrayTypeErrorUint16ArrayUint32ArrayUint8ArrayUint8ClampedArrayundefined
已棄用
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
已棄用
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
"物件"概觀物件與屬性EnumeratethepropertiesofanobjectCreatingnewobjectsInheritanceIndexingobjectpropertiesDefiningpropertiesforanobjecttypeDefiningmethodsUsingthisforobjectreferencesDefininggettersandsettersDeletingpropertiesComparingObjectsSeealso物件的使用
«前頁
次頁»(en-US)
JavaScriptisdesignedonasimpleobject-basedparadigm.Anobjectisacollectionofproperties,andapropertyisanassociationbetweenaname(orkey)andavalue.Aproperty'svaluecanbeafunction,inwhichcasethepropertyisknownasamethod.Inadditiontoobjectsthatarepredefinedinthebrowser,youcandefineyourownobjects.Thischapterdescribeshowtouseobjects,properties,functions,andmethods,andhowtocreateyourownobjects."物件"概觀就如同其他程式語言一般,JacaScript裡頭的"物件"可以與真實生活中的物件做類比。
其概念可以用生活中有形的物體來做理解。
在JavaScript裡,"物件"是一個擁有自己的屬性、型別、獨立的實體。
這裡我們以杯子舉例:我們可以從顏色、設計、重量、材質等方面來描述他的屬性。
同樣的,我們也可以用各種屬性來描述JavaScript中某個物體的特性。
物件與屬性JavaScript的物件有其關聯的屬性。
物件的屬性可以用附著在物件上的變數來描述。
ObjectpropertiesarebasicallythesameasordinaryJavaScriptvariables,exceptfortheattachmenttoobjects.Thepropertiesofanobjectdefinethecharacteristicsoftheobject.Youaccessthepropertiesofanobjectwithasimpledot-notation:
objectName.propertyName
LikeallJavaScriptvariables,boththeobjectname(whichcouldbeanormalvariable)andpropertynamearecasesensitive.Youcandefineapropertybyassigningitavalue.Forexample,let'screateanobjectnamedmyCarandgiveitpropertiesnamedmake,model,andyearasfollows:
varmyCar=newObject();
myCar.make='Ford';
myCar.model='Mustang';
myCar.year=1969;
Unassignedpropertiesofanobjectareundefined(andnotnull).
myCar.color;//undefined
PropertiesofJavaScriptobjectscanalsobeaccessedorsetusingabracketnotation(formoredetailsseepropertyaccessors(en-US)).Objectsaresometimescalledassociativearrays,sinceeachpropertyisassociatedwithastringvaluethatcanbeusedtoaccessit.So,forexample,youcouldaccessthepropertiesofthemyCarobjectasfollows:
myCar['make']='Ford';
myCar['model']='Mustang';
myCar['year']=1969;
AnobjectpropertynamecanbeanyvalidJavaScriptstring,oranythingthatcanbeconvertedtoastring,includingtheemptystring.However,anypropertynamethatisnotavalidJavaScriptidentifier(forexample,apropertynamethathasaspaceorahyphen,orthatstartswithanumber)canonlybeaccessedusingthesquarebracketnotation.Thisnotationisalsoveryusefulwhenpropertynamesaretobedynamicallydetermined(whenthepropertynameisnotdetermineduntilruntime).Examplesareasfollows:
//fourvariablesarecreatedandassignedinasinglego,
//separatedbycommas
varmyObj=newObject(),
str='myString',
rand=Math.random(),
obj=newObject();
myObj.type='Dotsyntax';
myObj['datecreated']='Stringwithspace';
myObj[str]='Stringvalue';
myObj[rand]='RandomNumber';
myObj[obj]='Object';
myObj['']='Evenanemptystring';
console.log(myObj);
PleasenotethatallkeysinthesquarebracketnotationareconvertedtoStringtype,sinceobjectsinJavaScriptcanonlyhaveStringtypeaskeytype.Forexample,intheabovecode,whenthekeyobjisaddedtothemyObj,JavaScriptwillcalltheobj.toString()method,andusethisresultstringasthenewkey.
Youcanalsoaccesspropertiesbyusingastringvaluethatisstoredinavariable:
varpropertyName='make';
myCar[propertyName]='Ford';
propertyName='model';
myCar[propertyName]='Mustang';
Youcanusethebracketnotationwithfor...intoiterateoveralltheenumerablepropertiesofanobject.Toillustratehowthisworks,thefollowingfunctiondisplaysthepropertiesoftheobjectwhenyoupasstheobjectandtheobject'snameasargumentstothefunction:
functionshowProps(obj,objName){
varresult='';
for(variinobj){
//obj.hasOwnProperty()isusedtofilteroutpropertiesfromtheobject'sprototypechain
if(obj.hasOwnProperty(i)){
result+=objName+'.'+i+'='+obj[i]+'\n';
}
}
returnresult;
}
So,thefunctioncallshowProps(myCar,"myCar")wouldreturnthefollowing:
myCar.make=Ford
myCar.model=Mustang
myCar.year=1969
EnumeratethepropertiesofanobjectStartingwithECMAScript5,therearethreenativewaystolist/traverseobjectproperties:
for...inloops
Thismethodtraversesallenumerablepropertiesofanobjectanditsprototypechain
Object.keys(o)
Thismethodreturnsanarraywithalltheown(notintheprototypechain)enumerableproperties'names("keys")ofanobjecto.
Object.getOwnPropertyNames(o)(en-US)
Thismethodreturnsanarraycontainingallownproperties'names(enumerableornot)ofanobjecto.
BeforeECMAScript5,therewasnonativewaytolistallpropertiesofanobject.However,thiscanbeachievedwiththefollowingfunction:
functionlistAllProperties(o){
varobjectToInspect;
varresult=[];
for(objectToInspect=o;objectToInspect!==null;objectToInspect=Object.getPrototypeOf(objectToInspect)){
result=result.concat(Object.getOwnPropertyNames(objectToInspect));
}
returnresult;
}
Thiscanbeusefultoreveal"hidden"properties(propertiesintheprototypechainwhicharenotaccessiblethroughtheobject,becauseanotherpropertyhasthesamenameearlierintheprototypechain).Listingaccessiblepropertiesonlycaneasilybedonebyremovingduplicatesinthearray.CreatingnewobjectsJavaScripthasanumberofpredefinedobjects.Inaddition,youcancreateyourownobjects.Youcancreateanobjectusinganobjectinitializer.Alternatively,youcanfirstcreateaconstructorfunctionandtheninstantiateanobjectinvokingthatfunctioninconjunctionwiththenewoperator.UsingobjectinitializersInadditiontocreatingobjectsusingaconstructorfunction,youcancreateobjectsusinganobjectinitializer.Usingobjectinitializersissometimesreferredtoascreatingobjectswithliteralnotation."Objectinitializer"isconsistentwiththeterminologyusedbyC++.
Thesyntaxforanobjectusinganobjectinitializeris:
varobj={property_1:value_1,//property_#maybeanidentifier...
2:value_2,//oranumber...
//...,
'propertyn':value_n};//orastring
whereobjisthenameofthenewobject,eachproperty_iisanidentifier(eitheraname,anumber,orastringliteral),andeachvalue_iisanexpressionwhosevalueisassignedtotheproperty_i.Theobjandassignmentisoptional;ifyoudonotneedtorefertothisobjectelsewhere,youdonotneedtoassignittoavariable.(Notethatyoumayneedtowraptheobjectliteralinparenthesesiftheobjectappearswhereastatementisexpected,soasnottohavetheliteralbeconfusedwithablockstatement.)
Objectinitializersareexpressions,andeachobjectinitializerresultsinanewobjectbeingcreatedwheneverthestatementinwhichitappearsisexecuted.Identicalobjectinitializerscreatedistinctobjectsthatwillnotcomparetoeachotherasequal.ObjectsarecreatedasifacalltonewObject()weremade;thatis,objectsmadefromobjectliteralexpressionsareinstancesofObject.
Thefollowingstatementcreatesanobjectandassignsittothevariablexifandonlyiftheexpressioncondistrue:
if(cond)varx={greeting:'hithere'};
ThefollowingexamplecreatesmyHondawiththreeproperties.Notethattheenginepropertyisalsoanobjectwithitsownproperties.
varmyHonda={color:'red',wheels:4,engine:{cylinders:4,size:2.2}};
Youcanalsouseobjectinitializerstocreatearrays.Seearrayliterals.UsingaconstructorfunctionAlternatively,youcancreateanobjectwiththesetwosteps:
Definetheobjecttypebywritingaconstructorfunction.Thereisastrongconvention,withgoodreason,touseacapitalinitialletter.
Createaninstanceoftheobjectwithnew.
Todefineanobjecttype,createafunctionfortheobjecttypethatspecifiesitsname,properties,andmethods.Forexample,supposeyouwanttocreateanobjecttypeforcars.Youwantthistypeofobjecttobecalledcar,andyouwantittohavepropertiesformake,model,andyear.Todothis,youwouldwritethefollowingfunction:
functionCar(make,model,year){
this.make=make;
this.model=model;
this.year=year;
}
Noticetheuseofthistoassignvaluestotheobject'spropertiesbasedonthevaluespassedtothefunction.
Nowyoucancreateanobjectcalledmycarasfollows:
varmycar=newCar('Eagle','TalonTSi',1993);
Thisstatementcreatesmycarandassignsitthespecifiedvaluesforitsproperties.Thenthevalueofmycar.makeisthestring"Eagle",mycar.yearistheinteger1993,andsoon.
Youcancreateanynumberofcarobjectsbycallstonew.Forexample,
varkenscar=newCar('Nissan','300ZX',1992);
varvpgscar=newCar('Mazda','Miata',1990);
Anobjectcanhaveapropertythatisitselfanotherobject.Forexample,supposeyoudefineanobjectcalledpersonasfollows:
functionPerson(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
andtheninstantiatetwonewpersonobjectsasfollows:
varrand=newPerson('RandMcKinnon',33,'M');
varken=newPerson('KenJones',39,'M');
Then,youcanrewritethedefinitionofcartoincludeanownerpropertythattakesapersonobject,asfollows:
functionCar(make,model,year,owner){
this.make=make;
this.model=model;
this.year=year;
this.owner=owner;
}
Toinstantiatethenewobjects,youthenusethefollowing:
varcar1=newCar('Eagle','TalonTSi',1993,rand);
varcar2=newCar('Nissan','300ZX',1992,ken);
Noticethatinsteadofpassingaliteralstringorintegervaluewhencreatingthenewobjects,theabovestatementspasstheobjectsrandandkenastheargumentsfortheowners.Thenifyouwanttofindoutthenameoftheownerofcar2,youcanaccessthefollowingproperty:
car2.owner.name
Notethatyoucanalwaysaddapropertytoapreviouslydefinedobject.Forexample,thestatement
car1.color='black';
addsapropertycolortocar1,andassignsitavalueof"black."However,thisdoesnotaffectanyotherobjects.Toaddthenewpropertytoallobjectsofthesametype,youhavetoaddthepropertytothedefinitionofthecarobjecttype.UsingtheObject.createmethodObjectscanalsobecreatedusingtheObject.create()method.Thismethodcanbeveryuseful,becauseitallowsyoutochoosetheprototypeobjectfortheobjectyouwanttocreate,withouthavingtodefineaconstructorfunction.
//Animalpropertiesandmethodencapsulation
varAnimal={
type:'Invertebrates',//Defaultvalueofproperties
displayType:function(){//MethodwhichwilldisplaytypeofAnimal
console.log(this.type);
}
};
//Createnewanimaltypecalledanimal1
varanimal1=Object.create(Animal);
animal1.displayType();//Output:Invertebrates
//CreatenewanimaltypecalledFishes
varfish=Object.create(Animal);
fish.type='Fishes';
fish.displayType();//Output:Fishes
InheritanceAllobjectsinJavaScriptinheritfromatleastoneotherobject.Theobjectbeinginheritedfromisknownastheprototype,andtheinheritedpropertiescanbefoundintheprototypeobjectoftheconstructor.SeeInheritanceandtheprototypechainformoreinformation.IndexingobjectpropertiesYoucanrefertoapropertyofanobjecteitherbyitspropertynameorbyitsordinalindex.Ifyouinitiallydefineapropertybyitsname,youmustalwaysrefertoitbyitsname,andifyouinitiallydefineapropertybyanindex,youmustalwaysrefertoitbyitsindex.
Thisrestrictionapplieswhenyoucreateanobjectanditspropertieswithaconstructorfunction(aswedidpreviouslywiththeCarobjecttype)andwhenyoudefineindividualpropertiesexplicitly(forexample,myCar.color="red").Ifyouinitiallydefineanobjectpropertywithanindex,suchasmyCar[5]="25mpg",yousubsequentlyrefertothepropertyonlyasmyCar[5].
TheexceptiontothisruleisobjectsreflectedfromHTML,suchastheformsarray.Youcanalwaysrefertoobjectsinthesearraysbyeithertheirordinalnumber(basedonwheretheyappearinthedocument)ortheirname(ifdefined).Forexample,ifthesecond
延伸文章資訊
- 1JavaScript Objects - W3Schools
Methods are actions that can be performed on objects. Object properties can be both primitive val...
- 2物件的使用 - JavaScript - MDN Web Docs
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties...
- 3JavaScript Object 物件 - Fooish 程式技術
JavaScript 物件(object) 是一個複合資料型態(composite data type),可以儲存不定數量的鍵值對(key-value paris),而一組鍵值對我們稱做物件的一...
- 4JS 常用API - Object.assign && Object.defineProperty - iT 邦幫忙
JS 原力覺醒Day27 - JS 常用API - Object.assign && Object.defineProperty. JavaScript 原力覺醒- 成為絕地武士之路系列第27 ...
- 5JavaScript Objects - W3Schools
JavaScript objects are containers for named values called properties. Object Methods. Objects can...