JavaScript ES6 Class Syntax - Cory Rylan

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

ES6 classes brings a new syntax for getters and setters on object properties Get and set allows us to run code on the reading or writing of a ... Articles Speaking Training Videos MynameisCoryRylan. GoogleDeveloperExpert,speaker,and SoftwareDeveloperatVMwareClarityDesignSystem. Follow@coryrylan CoryRylan Feb15,2015 -4minutes javascriptes2015 UpdatedFeb15,2015 ECMAScript2015ormorewellknownasES6isthenextspecificationforJavaScript.ES6bringsexcitingfeaturestoJavaScriptincludingnewsyntaximprovements.ThispostIamgoingtocoverthenewClasssyntax.JavaScripthasbeenaprototypalbasedlanguageusingobjectprototypestocreateobjectinheritanceandcodereuse.ThenewES6Classaddsanewsyntaxontopoftraditionalprototypes. SomethingIcannotstressenoughisthenewClassissyntacticsugaronprototypes.Underthehood,ES6Classesarestillusingprototypalinheritance.IfyouareunfamiliarwithprototypesIwouldsuggestyoureadmypreviouspostonJavaScriptPrototypalInheritance. Constructors InES5orthecurrentwidelysupportedversionofJavaScript,weuseprototypestocreateobjectinheritance.BeforeES6,weusedfunctionconstructorssimilartothis. //ES5ConstructorFunctionfunctionPerson(name){this.name=name;}varbob=newPerson('Bob');console.log(bob.name);//Outputs'Bob' ES2015/ES6hasthenewreservedkeywordClasswithaconstructorstatement.SotheES2015/ES6equivalentofourPersonfunctionconstructorwouldbethefollowing. //ES2015/ES6ClassclassPerson{constructor(name){this.name=name;}}letbob=newPerson('Bob');console.log(bob.name);//Outputs'Bob' Thenewsyntaxgivesusadedicatedconstructorstatementthatrunsonobject creation.Constructorsarehelpfulforanyobjectinitializationlogic. Methods Next,let'slookataddingafunctiontoourPerson.InES5wewouldhavehad somethinglikethis. //ES5addingamethodtothePersonprototypePerson.prototype.walk=function(){console.log(this.name+'iswalking.');};varbob=newPerson('Bob');bob.walk();//Outputs'Bobiswalking.' ES6offersusamuchmoreterseandcleansyntaxtoachievethesamegoal. //ES6ClassaddingamethodtothePersonprototypeclassPerson{constructor(name){this.name=name;}walk(){console.log(this.name+'iswalking.');}}letbob=newPerson('Bob');console.log(bob.name);//Outputs'Bobiswalking' GetandSet ES6classesbringsanewsyntaxforgettersandsettersonobjectpropertiesGetandsetallowsustoruncodeonthereadingorwritingofaproperty.ES5hadgettersandsettersaswellbutwasnotwidelyusedbecauseofolderIEbrowsers.ES5gettersandsettersdidnothaveasniceofasyntaxthatES6bringsus.Solet'screateagetandsetforournameproperty. //ES6getandsetclassPerson{constructor(name){this._name=name;}getname(){returnthis._name.toUpperCase();}setname(newName){this._name=newName;//validationcouldbecheckedheresuchasonlyallowingnonnumericalvalues}walk(){console.log(this._name+'iswalking.');}}letbob=newPerson('Bob');console.log(bob.name);//Outputs'BOB' Inourclassabovewehaveagetterandsetterforournameproperty.Weuse_conventiontocreateabackingfieldtostoreournameproperty.Withoutthiseverytimegetorsetiscalleditwouldcauseastackoverflow.Thegetwouldbecalledandwhichwouldcausethegettobecalledagainoverandovercreatinganinfiniteloop. Somethingtonoteisthatourbackingfieldthis._nameisnotprivate.Someonecouldstillaccessbob._nameandretrievetheproperty.Toachieveprivatestateonobjects,youwoulduseES6symbolandmoduletocreatetrueencapsulationandprivatestate.PrivatemethodscanbecreatedusingmoduleortraditionalclosuresusinganIIFE.UsinglanguageslikeTypeScriptyoucangetcompile-timeenforcementofprivatepropertiesandmethods. Inheritance Nowlet'slookintoinheritanceusingtraditionalprototypesinES5syntax.WewillcreateaProgrammerobjecttoinheritourPersonobject.OurprogrammerobjectwillinheritpersonandalsohaveawriteCode()method. //ES5PrototypeinheritancefunctionProgrammer(name,programmingLanguage){this.name=name;this.programmingLanguage=programmingLanguage;}Programmer.prototype=Object.create(Person.prototype);Programmer.prototype.constructor=Programmer;Programmer.prototype.writeCode=function(){console.log(this.name+'iscodingin'+this.programmingLanguage+'.');};varcory=newProgrammer('Cory','JavaScript');cory.walk();//Outputs'Coryiswalking.'cory.writeCode();//Outputs'CoryiscodinginJavaScript.' Nowlet'slookatthenewES6Classsyntaxforinheritanceusingtheextendkeyword. classProgrammerextendsPerson{constructor(name,programmingLanguage){super(name);this.programmingLanguage=programmingLanguage;}writeCode(){console.log(this._name+'iscodingin'+this._programmingLanguage+'.');}}letcory=newProgrammer('Cory','JavaScript');cory.walk();//Outputs'Coryiswalking.'cory.writeCode();//Outputs'CoryiscodinginJavaScript.' Youcanseetheclasssyntaxoffersacleansyntaxforprototypalinheritance.Onedetailyoumaynoticeisthesuper()keyword.Thesuperkeywordletsuscalltheparentobjectthatisbeinginherited.Itisgoodadvicetoavoidthisasthiscancauseaneventightercouplingbetweenyourobjects,butthereareoccasionswhereitisappropriatetouse.Inthiscase,itcanbeusedintheconstructortoassigntothesuperconstructor.IfthePersonconstructorcontainedanylogic,customgettersorsettersforthenamepropertywewouldwanttousethesuperandnotduplicatethelogicintheProgrammerclass.Ifaconstructorisnotdefinedonachildclassthesuperclassconstructorwillbeinvokedbydefault. Overview HereisonefinallookatourPersonandProgrammerclasses.Thegettersandsettersarenotnecessaryinthisusecasebutaretheretodemonstratethenewsyntax. classPerson{constructor(name){this._name=name;}getname(){returnthis._name;}setname(newName){this._name=newName;}walk(){console.log(this._name+'iswalking.');}}classProgrammerextendsPerson{constructor(name,programmingLanguage){super(name);this._programmingLanguage=programmingLanguage;}getprogrammingLanguage(){returnthis._programmingLanguage;}setprogrammingLanguage(newprogrammingLanguage){this._programmingLanguage=newprogrammingLanguage;}writeCode(){console.log(this._name+'iscodingin'+this._programmingLanguage+'.');}}letbob=newPerson('Bob');bob.walk();letcory=newProgrammer('Cory','JavaScript');cory.walk();cory.writeCode();console.log(cory.name); Acodepen.iodemoofthecodeabovecanbefoundhere.ES6classesbringsomesyntacticalsugartoprototypes.JustrememberthatisallES6classesare,syntacticsugar.Rememberclassesarejustoneofmanyoptionstoorganizeandstructurecode.Therearemanyothergreatdesignpatternsforcodereusesuchasthemodulepattern. ES6bringssomegreatimprovementstomakingJavaScriptamoreproductiveprogramminglanguageandisalreadybeingimplementedinbrowserstoday.TostartwritingES6todaycheckoutBabelJS(formerly6to5)atranspilerthattranspileES6JavaScripttoES5. WebComponentEssentials Savedevelopmenttime,improveproductconsistencyandshipeverywhere. WiththisnewCourseandE-BooklearnhowtobuildUIcomponentsthat workinanyJavaScriptframeworksuchasAngular, Vue,React,andmore! Startbuildingnow! WebComponentEssentials ReusableUIComponentsforallyourWebApplications StartBuildingNow!   Signuptogetthelatestdevpostsandcontent! Nospam.ShortoccasionalupdatesonWebDevelopmentarticles,videos,andnewcoursesinyourinbox. Subscribe  RelatedPosts UseJavaScriptDateObjectswiththeHTML5DatePicker Mar31,2021 LearnhowtoeasilyuseboththenativeHTML5datepickerandJavaScriptDateobjectstogether. ReadArticle DesignSystemPerformancewithClarityCoreWebComponents Nov11,2020 LearnhowtobuildhighperformanceUIandDesignSystemsontheWebusingClarityCore. ReadArticle StateofWebComponentsin2020 Oct29,2020 LearnabriefoverviewonWebComponentsandthelatesttechavailabletobuildanddistributecomponentsacrosstheWeb. ReadArticle



請為這篇文章評分?