JavaScript ES6 Class Syntax - Cory Rylan
文章推薦指數: 80 %
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
延伸文章資訊
- 1getters and setters in JavaScript classes? - Tutorialspoint
Classes allow using getters and setters. It is smart to use getters and setters for the propertie...
- 2Introduction to JavaScript getters and setters in ES6
In this tutorial, you will learn about JavaScript getters and setters in ES6 and how to use them ...
- 3JavaScript Object Accessors - W3Schools
ECMAScript 5 (ES5 2009) introduced Getter and Setters. Getters and setters allow you to define Ob...
- 4[JS] Getter and Setter 筆記 - pcwu's TIL Notes
JavaScript. 在JavaScript 中如果Class 在取屬性值或設定屬性值時,如果有比較複雜的運用時,可以使用 Getter 和 Setter 。
- 5getter - JavaScript - MDN Web Docs
儘管可以用getter 與setter 的關聯建立虛擬屬性的類型,但getter 無法被綁 ... class Example { get hello() { return 'world'; }...