物件的使用 - 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 ...
SkiptomaincontentSkiptoselectlanguage給開發者的網頁技術文件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
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
"物件"概觀物件與屬性EnumeratethepropertiesofanobjectCreatingnewobjectsInheritanceIndexingobjectpropertiesDefiningpropertiesforanobjecttypeDefiningmethodsUsingthisforobjectreferencesDefininggettersandsettersDeletingpropertiesComparingObjectsSeealso物件的使用
«前頁
次頁»
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).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=1969EnumeratethepropertiesofanobjectStartingwithECMAScript5,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:FishesInheritanceAllobjectsinJavaScriptinheritfromatleastoneotherobject.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
延伸文章資訊
- 1Private properties in JavaScript ES6 classes - Stack Overflow
Short answer, no, there is no native support for private properties with ES6 classes. But you cou...
- 2Class basic syntax - The Modern JavaScript Tutorial
First, a function created by class is labelled by a special internal property [[IsClassConstructo...
- 3物件的使用 - JavaScript - MDN Web Docs
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties...
- 4JavaScript Class (類別) - Shubo 的程式開發筆記
這篇文章將會解釋JavaScript class 的觀念以及使用方法,包含class ... 這種Arrow Functions in Class Properties 的寫法,非常有用,可以用...
- 5JavaScript | ES6 中最容易誤會的語法糖Class - 基本用法
Class 內部會描述Properties 和Method。 Class 能建構出Object ,也被稱作Instance 。 Instance 能夠使用Class 內的Method,並藉由Me...