物件的使用 - 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 ... 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

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(ortheObject.prototype.__defineGetter__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. TolearnaboutECMAScript2015classes(anewwaytocreateobjects),readtheJavaScriptclasseschapter. «前頁 次頁» Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Feb15,2022,byMDNcontributors


請為這篇文章評分?