JavaScript Class Fundamentals: Introduction to ES6 Class

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

A JavaScript class is a blueprint for creating objects. A class encapsulates data and functions that manipulate data. Unlike other programming languages such as ... SkiptocontentHome»JavaScriptTutorial»JavaScriptClassSummary:inthistutorial,you’lllearnabouttheJavaScriptclassandhowtouseiteffectively.AJavaScriptclassisablueprintforcreatingobjects.Aclassencapsulatesdataandfunctionsthatmanipulatedata.UnlikeotherprogramminglanguagessuchasJavaandC#,JavaScriptclassesaresyntacticsugarovertheprototypalinheritance.Inotherwords,ES6classesarejustspecialfunctions.ClassespriortoES6revisitedPriortoES6,JavaScripthadnoconceptsofclasses.Tomimicaclass,youoftenusetheconstructor/prototypepatternasshowninthefollowingexample:functionPerson(name){ this.name=name; } Person.prototype.getName=function(){ returnthis.name; }; varjohn=newPerson("JohnDoe"); console.log(john.getName());Codelanguage:JavaScript(javascript)Output:JohnDoeHowitworks.First,createthePersonasaconstructorfunctionthathasapropertynamecalledname.ThegetName()functionisassignedtotheprototypesothatitcanbesharedbyallinstancesofthePersontype.Then,createanewinstanceofthePersontypeusingthenewoperator.Thejohnobject,hence,isaninstanceofthePersonandObjectthroughprototypalinheritance.ThefollowingstatementsusetheinstanceofoperatortocheckifjohnisaninstanceofthePersonandObjecttype:console.log(johninstanceofPerson);//true console.log(johninstanceofObject);//trueCodelanguage:JavaScript(javascript)ES6classdeclarationES6introducedanewsyntaxfordeclaringaclassasshowninthisexample:classPerson{ constructor(name){ this.name=name; } getName(){ returnthis.name; } }Codelanguage:JavaScript(javascript)ThisPersonclassbehaveslikethePersontypeinthepreviousexample.However,insteadofusingaconstructor/prototypepattern,itusestheclasskeyword.InthePersonclass,theconstructor()iswhereyoucaninitializethepropertiesofaninstance.JavaScriptautomaticallycallstheconstructor()methodwhenyouinstantiateanobjectoftheclass.ThefollowingcreatesanewPersonobject,whichwillautomaticallycalltheconstructor()ofthePersonclass:letjohn=newPerson("JohnDoe");Codelanguage:JavaScript(javascript)ThegetName()iscalledamethodofthePersonclass.Likeaconstructorfunction,youcancallthemethodsofaclassusingthefollowingsyntax:objectName.methodName(args)Codelanguage:CSS(css)Forexample:letname=john.getName(); console.log(name);//"JohnDoe"Codelanguage:JavaScript(javascript)Toverifythefactthatclassesarespecialfunctions,youcanusethetypeofoperatoroftocheckthetypeofthePersonclass.console.log(typeofPerson);//functionCodelanguage:JavaScript(javascript)Itreturnsfunctionasexpected.ThejohnobjectisalsoaninstanceofthePersonandObjecttypes:console.log(johninstanceofPerson);//true console.log(johninstanceofObject);//trueCodelanguage:JavaScript(javascript)Classvs.CustomtypeDespitethesimilaritiesbetweenaclassandacustomtypedefinedviaaconstructorfunction,therearesomeimportantdifferences.First,classdeclarationsarenothoistedlikefunctiondeclarations.Forexample,ifyouplacethefollowingcodeabovethePersonclassdeclarationsection,youwillgetaReferenceError.letjohn=newPerson("JohnDoe");Codelanguage:JavaScript(javascript)Error:UncaughtReferenceError:PersonisnotdefinedCodelanguage:JavaScript(javascript)Second,allthecodeinsideaclassautomaticallyexecutesinthestrictmode.Andyoucannotchangethisbehavior.Third,classmethodsarenon-enumerable.Ifyouuseaconstructor/prototypepattern,youhavetousetheObject.defineProperty()methodtomakeapropertynon-enumerable.Finally,callingtheclassconstructorwithoutthenewoperatorwillresultinanerrorasshowninthefollowingexample.letjohn=Person("JohnDoe");Codelanguage:JavaScript(javascript)Error:UncaughtTypeError:ClassconstructorPersoncannotbeinvokedwithout'new'Codelanguage:JavaScript(javascript)Notethatit’spossibletocalltheconstructorfunctionwithoutthenewoperator.Inthiscase,theconstructorfunctionbehaveslikearegularfunction.SummaryUseJavaScriptclasskeyworddeclaresanewclass.Aclassdeclarationissyntacticsugaroverprototypalinheritancewithadditionalenhancements.PreviouslyObjectLiteralSyntaxExtensionsinES6UpNextJavaScriptGettersandSettersSearchfor:GettingStartedJavaScriptFundamentalsJavaScriptOperatorsControlFlowJavaScriptFunctionsJavaScriptObjectsClassesAdvancedFunctionsPromises&Async/AwaitJavaScriptModulesJavascriptErrorHandlingJavaScriptRuntime



請為這篇文章評分?