JavaScript Classes - W3Schools

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

Class methods are created with the same syntax as object methods. Use the keyword class to create a class. Always add a constructor() method. Then add any ... Tutorials References Exercises Videos ProNEW Menu Login PaidCourses WebsiteNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C++ C# R React Kotlin    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 ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility 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 SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz XMLQuiz CyberSecurityQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop Pro JSTutorial JSHOME JSIntroduction JSWhereTo JSOutput JSStatements JSSyntax JSComments JSVariables JSLet JSConst JSOperators JSArithmetic JSAssignment JSDataTypes JSFunctions JSObjects JSEvents JSStrings JSStringMethods JSStringSearch JSStringTemplates JSNumbers JSNumberMethods JSArrays JSArrayMethods JSArraySort JSArrayIteration JSArrayConst JSDates JSDateFormats JSDateGetMethods JSDateSetMethods JSMath JSRandom JSBooleans JSComparisons JSConditions 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 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 JavaScriptClasses ❮Previous Next❯ ECMAScript2015,alsoknownasES6,introducedJavaScriptClasses. JavaScriptClassesaretemplatesforJavaScriptObjects. JavaScriptClassSyntax Usethekeywordclasstocreateaclass. Alwaysaddamethodnamedconstructor(): Syntax classClassName{  constructor(){...} } Example classCar{  constructor(name,year){    this.name=name;    this.year=year;  } } Theexampleabovecreatesaclassnamed"Car". Theclasshastwoinitialproperties:"name"and"year". AJavaScriptclassisnotanobject. ItisatemplateforJavaScriptobjects. UsingaClass Whenyouhaveaclass,youcanusetheclasstocreateobjects: Example letmyCar1=newCar("Ford",2014); letmyCar2=newCar("Audi",2019); TryitYourself» TheexampleaboveusestheCarclasstocreatetwoCarobjects. Theconstructormethodiscalledautomaticallywhenanewobjectiscreated. TheConstructorMethod Theconstructormethodisaspecialmethod: Ithastohavetheexactname"constructor" Itisexecutedautomaticallywhenanewobjectiscreated Itisusedtoinitializeobjectproperties Ifyoudonotdefineaconstructormethod,JavaScript willaddanemptyconstructormethod. ClassMethods Classmethodsarecreatedwiththesamesyntaxasobjectmethods. Usethekeywordclasstocreateaclass. Alwaysaddaconstructor()method. Thenaddanynumberofmethods. Syntax classClassName{  constructor(){...}   method_1(){...}   method_2(){...}   method_3(){...} } CreateaClassmethodnamed"age",thatreturnstheCarage: Example classCar{  constructor(name,year){    this.name=name;    this.year=year;  } age(){    letdate=newDate();    returndate.getFullYear()-this.year;  }} letmyCar=newCar("Ford",2014); document.getElementById("demo").innerHTML= "Mycaris"+myCar.age()+"yearsold."; TryitYourself» YoucansendparameterstoClassmethods: Example classCar{ constructor(name,year){    this.name=name;   this.year=year; }  age(x){   returnx-this.year; }} letdate=newDate(); letyear=date.getFullYear();letmyCar=new Car("Ford",2014);document.getElementById("demo").innerHTML="Mycaris "+myCar.age(year)+"yearsold."; TryitYourself» BrowserSupport Thefollowingtabledefinesthefirstbrowserversionwithfullsupportfor ClassesinJavaScript: Chrome49 Edge12 Firefox45 Safari9 Opera36 Mar,2016 Jul,2015 Mar,2016 Oct,2015 Mar,2016 YouwilllearnalotmoreaboutJavaScriptClasseslaterinthistutorial. ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?