JavaScript Objects - W3Schools
文章推薦指數: 80 %
JavaScript objects are containers for named values called properties. Object Methods. Objects can also have methods. Methods are actions that can be performed ... Tutorials References Exercises Videos Menu Login FreeWebsite GetCertified Pro HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOWTO W3.CSS C C++ C# REACT R JQUERY DJANGO TYPESCRIPT NODEJS MYSQL Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility Blog DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises PythonExercises SQLExercises PHPExercises JavaExercises CExercises C++Exercises C#Exercises jQueryExercises React.jsExercises MySQLExercises Bootstrap5Exercises Bootstrap4Exercises Bootstrap3Exercises NumPyExercises PandasExercises SciPyExercises TypeScriptExercises ExcelExercises RExercises GitExercises KotlinExercises GoExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz PythonQuiz SQLQuiz PHPQuiz JavaQuiz CQuiz C++Quiz C#Quiz jQueryQuiz React.jsQuiz MySQLQuiz Bootstrap5Quiz Bootstrap4Quiz Bootstrap3Quiz NumPyQuiz PandasQuiz SciPyQuiz TypeScriptQuiz XMLQuiz RQuiz GitQuiz KotlinQuiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse PythonCourse SQLCourse PHPCourse JavaCourse C++Course C#Course jQueryCourse React.jsCourse Bootstrap4Course Bootstrap3Course NumPyCourse PandasCourse TypeScriptCourse XMLCourse RCourse DataAnalyticsCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate PythonCertificate SQLCertificate PHPCertificate JavaCertificate C++Certificate C#Certificate jQueryCertificate React.jsCertificate MySQLCertificate Bootstrap5Certificate Bootstrap4Certificate Bootstrap3Certificate TypeScriptCertificate XMLCertificate ExcelCertificate DataScienceCertificate CyberSecurityCertificate AccessibilityCertificate × Tutorials References Exercises GetCertified Spaces Videos Shop Pro JSTutorial JSHOME JSIntroduction JSWhereTo JSOutput JSStatements JSSyntax JSComments JSVariables JSLet JSConst JSOperators JSArithmetic JSAssignment JSPrecedence JSDataTypes JSFunctions JSObjects JSEvents JSStrings JSStringMethods JSStringSearch JSStringTemplates JSNumbers JSNumberMethods JSArrays JSArrayMethods JSArraySort JSArrayIteration JSArrayConst JSDates JSDateFormats JSDateGetMethods JSDateSetMethods JSMath JSRandom JSBooleans JSComparisons JSIfElse JSSwitch JSLoopFor JSLoopForIn JSLoopForOf JSLoopWhile JSBreak JSIterables JSSets JSMaps JSTypeof JSTypeConversion JSBitwise JSRegExp JSErrors JSScope JSHoisting JSStrictMode JSthisKeyword JSArrowFunction JSClasses JSModules JSJSON JSDebugging JSStyleGuide JSBestPractices JSMistakes JSPerformance JSReservedWords JSVersions JSVersions JS2009(ES5) JS2015(ES6) JS2016 JS2017 JS2018 JS2019/2020 JSIE/Edge JSHistory JSObjects ObjectDefinitions ObjectProperties ObjectMethods ObjectDisplay ObjectAccessors ObjectConstructors ObjectPrototypes ObjectIterables ObjectSets ObjectMaps ObjectReference JSFunctions FunctionDefinitions FunctionParameters FunctionInvocation FunctionCall FunctionApply FunctionBind FunctionClosures JSClasses ClassIntro ClassInheritance ClassStatic JSAsync JSCallbacks JSAsynchronous JSPromises JSAsync/Await JSHTMLDOM DOMIntro DOMMethods DOMDocument DOMElements DOMHTML DOMForms DOMCSS DOMAnimations DOMEvents DOMEventListener DOMNavigation DOMNodes DOMCollections DOMNodeLists JSBrowserBOM JSWindow JSScreen JSLocation JSHistory JSNavigator JSPopupAlert JSTiming JSCookies JSWebAPIs WebAPIIntro WebFormsAPI WebHistoryAPI WebStorageAPI WebWorkerAPI WebFetchAPI WebGeolocationAPI JSAJAX AJAXIntro AJAXXMLHttp AJAXRequest AJAXResponse AJAXXMLFile AJAXPHP AJAXASP AJAXDatabase AJAXApplications AJAXExamples JSJSON JSONIntro JSONSyntax JSONvsXML JSONDataTypes JSONParse JSONStringify JSONObjects JSONArrays JSONServer JSONPHP JSONHTML JSONJSONP JSvsjQuery jQuerySelectors jQueryHTML jQueryCSS jQueryDOM JSGraphics JSGraphics JSCanvas JSPlotly JSChart.js JSGoogleChart JSD3.js JSExamples JSExamples JSHTMLDOM JSHTMLInput JSHTMLObjects JSHTMLEvents JSBrowser JSEditor JSExercises JSQuiz JSCertificate JSReferences JavaScriptObjects HTMLDOMObjects JavaScriptObjects ❮Previous Next❯ RealLifeObjects,Properties,andMethods Inreallife,acarisanobject. Acarhaspropertieslikeweightandcolor,andmethodslikestartandstop: Object Properties Methods car.name=Fiat car.model=500 car.weight=850kg car.color=white car.start() car.drive() car.brake() car.stop() Allcarshavethesameproperties,butthepropertyvaluesdifferfromcartocar. Allcarshavethesamemethods,butthemethodsareperformed atdifferenttimes. JavaScriptObjects YouhavealreadylearnedthatJavaScriptvariablesare containersfordatavalues. Thiscodeassignsasimplevalue(Fiat)to avariablenamedcar: letcar="Fiat"; TryitYourself» Objectsarevariablestoo.Butobjectscancontainmany values. Thiscodeassignsmanyvalues(Fiat,500,white)toa variable namedcar: constcar={type:"Fiat",model:"500",color:"white"}; TryitYourself» Thevaluesarewrittenasname:valuepairs(nameandvalueseparatedbya colon). Itisacommonpracticetodeclareobjectswiththeconstkeyword. Learnmoreaboutusingconstwithobjectsinthechapter:JSConst. ObjectDefinition Youdefine(andcreate)aJavaScriptobjectwithanobjectliteral: Example constperson={firstName:"John",lastName:"Doe",age:50,eyeColor:"blue"}; TryitYourself» Spacesandlinebreaksarenotimportant.Anobjectdefinitioncanspanmultiplelines: Example constperson={ firstName:"John", lastName:"Doe", age:50, eyeColor:"blue" }; TryitYourself» ObjectProperties Thename:valuespairsinJavaScriptobjectsarecalledproperties: Property PropertyValue firstName John lastName Doe age 50 eyeColor blue AccessingObjectProperties Youcanaccessobjectpropertiesintwoways: objectName.propertyName or objectName["propertyName"] Example1 person.lastName; TryitYourself» Example2 person["lastName"]; TryitYourself» JavaScriptobjectsarecontainersfornamedvaluescalledproperties. ObjectMethods Objectscanalsohavemethods. Methodsareactionsthatcanbeperformedonobjects. Methodsarestoredinpropertiesasfunction definitions. Property PropertyValue firstName John lastName Doe age 50 eyeColor blue fullName function(){returnthis.firstName+""+this.lastName;} Amethodisafunctionstoredasaproperty. Example constperson={ firstName:"John", lastName:"Doe", id : 5566, fullName:function(){ returnthis.firstName+""+this.lastName; } }; Intheexampleabove,thisreferstothepersonobject. I.E.this.firstNamemeansthefirstNamepropertyofthis. I.E.this.firstNamemeansthefirstNamepropertyofperson. Whatisthis? InJavaScript,thethiskeywordreferstoanobject. Whichobjectdependsonhowthisisbeinginvoked(usedorcalled). Thethiskeywordreferstodifferentobjectsdependingonhowitisused: Inanobjectmethod,thisreferstotheobject. Alone,thisreferstotheglobalobject. Inafunction,thisreferstotheglobalobject. Inafunction,instrictmode,thisisundefined. Inanevent,thisreferstotheelementthatreceivedtheevent. Methodslikecall(),apply(), andbind()canreferthistoanyobject. Note thisisnotavariable.Itisakeyword.Youcannotchangethevalueofthis. SeeAlso: TheJavaScriptthisTutorial ThethisKeyword Inafunctiondefinition,thisreferstothe"owner"ofthefunction. Intheexampleabove,thisisthepersonobjectthat"owns"the fullNamefunction. Inotherwords,this.firstNamemeansthefirstNamepropertyofthisobject. LearnmoreaboutthisinTheJavaScriptthisTutorial. AccessingObjectMethods Youaccessanobjectmethodwiththefollowingsyntax: objectName.methodName() Example name=person.fullName(); TryitYourself» Ifyouaccessamethodwithoutthe()parentheses,it willreturnthefunctiondefinition: Example name=person.fullName; TryitYourself» DoNotDeclareStrings,Numbers,andBooleansasObjects! WhenaJavaScriptvariableisdeclaredwiththekeyword"new",thevariableis createdas anobject: x=newString(); //DeclaresxasaStringobject y= newNumber(); //DeclaresyasaNumberobject z= newBoolean(); //DeclareszasaBooleanobject AvoidString,Number,andBooleanobjects.Theycomplicateyourcodeandslowdown executionspeed. Youwilllearnmoreaboutobjectslaterinthistutorial. TestYourselfWithExercises Exercise: Alert"John"byextractinginformationfromthepersonobject. constperson={ firstName:"John", lastName:"Doe" }; alert(); SubmitAnswer» StarttheExercise ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1JS 常用API - Object.assign && Object.defineProperty - iT 邦幫忙
JS 原力覺醒Day27 - JS 常用API - Object.assign && Object.defineProperty. JavaScript 原力覺醒- 成為絕地武士之路系列第27 ...
- 2JavaScript 物件基礎概念- 學習該如何開發Web | MDN
基本的電腦素養、對HTML 與CSS 已有初步認識、熟悉JavaScript 基本概念(參閱〈First steps〉與〈Building blocks〉)。 主旨:, 了解「物件導向(OO)」...
- 3Object.assign() - JavaScript - MDN Web Docs
注意: Object.assign() 不會在來源物件屬性的值為 null 或 undefined 的時候拋出錯誤。 範例. 複製物件. var obj = { a ...
- 4JavaScript Object 物件 - Fooish 程式技術
JavaScript 物件(object) 是一個複合資料型態(composite data type),可以儲存不定數量的鍵值對(key-value paris),而一組鍵值對我們稱做物件的一...
- 5JavaScript Objects - W3Schools
Methods are actions that can be performed on objects. Object properties can be both primitive val...