物件的使用 - JavaScript - MDN Web Docs

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

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

taginadocumenthasaNAMEattributeof"myForm",youcanrefertotheformasdocument.forms[1]ordocument.forms["myForm"]ordocument.forms.myForm.DefiningpropertiesforanobjecttypeYoucanaddapropertytoapreviouslydefinedobjecttypebyusingtheprototypeproperty.Thisdefinesapropertythatissharedbyallobjectsofthespecifiedtype,ratherthanbyjustoneinstanceoftheobject.Thefollowingcodeaddsacolorpropertytoallobjectsoftypecar,andthenassignsavaluetothecolorpropertyoftheobjectcar1. Car.prototype.color=null; car1.color='black'; SeetheprototypepropertyoftheFunctionobjectintheJavaScriptreferenceformoreinformation.DefiningmethodsAmethodisafunctionassociatedwithanobject,or,simplyput,amethodisapropertyofanobjectthatisafunction.Methodsaredefinedthewaynormalfunctionsaredefined,exceptthattheyhavetobeassignedasthepropertyofanobject.Seealsomethoddefinitionsformoredetails.Anexampleis: objectName.methodname=function_name; varmyObj={ myMethod:function(params){ //...dosomething } //ORTHISWORKSTOO myOtherMethod(params){ //...dosomethingelse } }; whereobjectNameisanexistingobject,methodnameisthenameyouareassigningtothemethod,andfunction_nameisthenameofthefunction. Youcanthencallthemethodinthecontextoftheobjectasfollows: object.methodname(params); Youcandefinemethodsforanobjecttypebyincludingamethoddefinitionintheobjectconstructorfunction.Youcoulddefineafunctionthatwouldformatanddisplaythepropertiesofthepreviously-definedcarobjects;forexample, functiondisplayCar(){ varresult='ABeautiful'+this.year+''+this.make +''+this.model; pretty_print(result); } wherepretty_printisafunctiontodisplayahorizontalruleandastring.Noticetheuseofthistorefertotheobjecttowhichthemethodbelongs. Youcanmakethisfunctionamethodofcarbyaddingthestatement this.displayCar=displayCar; totheobjectdefinition.So,thefulldefinitionofcarwouldnowlooklike functionCar(make,model,year,owner){ this.make=make; this.model=model; this.year=year; this.owner=owner; this.displayCar=displayCar; } ThenyoucancallthedisplayCarmethodforeachoftheobjectsasfollows: car1.displayCar(); car2.displayCar(); UsingthisforobjectreferencesJavaScripthasaspecialkeyword,this,thatyoucanusewithinamethodtorefertothecurrentobject.Forexample,supposeyouhaveafunctioncalledvalidatethatvalidatesanobject'svalueproperty,giventheobjectandthehighandlowvalues: functionvalidate(obj,lowval,hival){ if((obj.valuehival)){ alert('InvalidValue!'); } } Then,youcouldcallvalidateineachformelement'sonchangeeventhandler,usingthistopassittheelement,asinthefollowingexample: Ingeneral,thisreferstothecallingobjectinamethod. Whencombinedwiththeformproperty,thiscanrefertothecurrentobject'sparentform.Inthefollowingexample,theformmyFormcontainsaTextobjectandabutton.Whentheuserclicksthebutton,thevalueoftheTextobjectissettotheform'sname.Thebutton'sonclickeventhandlerusesthis.formtorefertotheparentform,myForm.

DefininggettersandsettersAgetterisamethodthatgetsthevalueofaspecificproperty.Asetterisamethodthatsetsthevalueofaspecificproperty.Youcandefinegettersandsettersonanypredefinedcoreobjectoruser-definedobjectthatsupportstheadditionofnewproperties.Thesyntaxfordefininggettersandsettersusestheobjectliteralsyntax. Thefollowingillustrateshowgettersandsetterscouldworkforauser-definedobjecto. varo={ a:7, getb(){ returnthis.a+1; }, setc(x){ this.a=x/2; } }; console.log(o.a);//7 console.log(o.b);//8 o.c=50; console.log(o.a);//25 Theoobject'spropertiesare: o.a—anumber o.b—agetterthatreturnso.aplus1 o.c—asetterthatsetsthevalueofo.atohalfofthevalueo.cisbeingsetto Pleasenotethatfunctionnamesofgettersandsettersdefinedinanobjectliteralusing"[gs]etproperty()"(asopposedto__define[GS]etter__)arenotthenamesofthegettersthemselves,eventhoughthe[gs]etpropertyName(){}syntaxmaymisleadyoutothinkotherwise.Tonameafunctioninagetterorsetterusingthe"[gs]etproperty()"syntax,defineanexplicitlynamedfunctionprogrammaticallyusingObject.defineProperty(en-US)(ortheObject.prototype.__defineGetter__(en-US)legacyfallback). ThefollowingcodeillustrateshowgettersandsetterscanextendtheDateprototypetoaddayearpropertytoallinstancesofthepredefinedDateclass.ItusestheDateclass'sexistinggetFullYearandsetFullYearmethodstosupporttheyearproperty'sgetterandsetter. Thesestatementsdefineagetterandsetterfortheyearproperty: vard=Date.prototype; Object.defineProperty(d,'year',{ get:function(){returnthis.getFullYear();}, set:function(y){this.setFullYear(y);} }); ThesestatementsusethegetterandsetterinaDateobject: varnow=newDate(); console.log(now.year);//2000 now.year=2001;//987617605170 console.log(now); //WedApr1811:13:25GMT-0700(PacificDaylightTime)2001 Inprinciple,gettersandsetterscanbeeither definedusingobjectinitializers,or addedlatertoanyobjectatanytimeusingagetterorsetteraddingmethod. Whendefininggettersandsettersusingobjectinitializersallyouneedtodoistoprefixagettermethodwithgetandasettermethodwithset.Ofcourse,thegettermethodmustnotexpectaparameter,whilethesettermethodexpectsexactlyoneparameter(thenewvaluetoset).Forinstance: varo={ a:7, getb(){returnthis.a+1;}, setc(x){this.a=x/2;} }; GettersandsetterscanalsobeaddedtoanobjectatanytimeaftercreationusingtheObject.definePropertiesmethod.Thismethod'sfirstparameteristheobjectonwhichyouwanttodefinethegetterorsetter.Thesecondparameterisanobjectwhosepropertynamesarethegetterorsetternames,andwhosepropertyvaluesareobjectsfordefiningthegetterorsetterfunctions.Here'sanexamplethatdefinesthesamegetterandsetterusedinthepreviousexample: varo={a:0}; Object.defineProperties(o,{ 'b':{get:function(){returnthis.a+1;}}, 'c':{set:function(x){this.a=x/2;}} }); o.c=10;//Runsthesetter,whichassigns10/2(5)tothe'a'property console.log(o.b);//Runsthegetter,whichyieldsa+1or6 Whichofthetwoformstochoosedependsonyourprogrammingstyleandtaskathand.Ifyoualreadygofortheobjectinitializerwhendefiningaprototypeyouwillprobablymostofthetimechoosethefirstform.Thisformismorecompactandnatural.However,ifyouneedtoaddgettersandsetterslater—becauseyoudidnotwritetheprototypeorparticularobject—thenthesecondformistheonlypossibleform.ThesecondformprobablybestrepresentsthedynamicnatureofJavaScript—butitcanmakethecodehardtoreadandunderstand.DeletingpropertiesYoucanremoveanon-inheritedpropertybyusingthedeleteoperator.Thefollowingcodeshowshowtoremoveaproperty. //Createsanewobject,myobj,withtwoproperties,aandb. varmyobj=newObject; myobj.a=5; myobj.b=12; //Removestheaproperty,leavingmyobjwithonlythebproperty. deletemyobj.a; console.log('a'inmyobj);//yields"false" Youcanalsousedeletetodeleteaglobalvariableifthevarkeywordwasnotusedtodeclarethevariable: g=17; deleteg; ComparingObjectsInJavaScriptobjectsareareferencetype.Twodistinctobjectsareneverequal,eveniftheyhavethesameproperties.Onlycomparingthesameobjectreferencewithitselfyieldstrue. //Twovariables,twodistinctobjectswiththesameproperties varfruit={name:'apple'}; varfruitbear={name:'apple'}; fruit==fruitbear;//returnfalse fruit===fruitbear;//returnfalse //Twovariables,asingleobject varfruit={name:'apple'}; varfruitbear=fruit;//assignfruitobjectreferencetofruitbear //herefruitandfruitbeararepointingtosameobject fruit==fruitbear;//returntrue fruit===fruitbear;//returntrue fruit.name='grape'; console.log(fruitbear);//yields{name:"grape"}insteadof{name:"apple"} Formoreinformationaboutcomparisonoperators,seeComparisonoperators.Seealso Todivedeeper,readaboutthedetailsofjavaScript'sobjectsmodel(en-US). TolearnaboutECMAScript2015classes(anewwaytocreateobjects),readtheJavaScriptclasseschapter. «前頁 次頁»(en-US) Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:2022年9月20日,byMDNcontributors


請為這篇文章評分?