JavaScript Class Fundamentals: Introduction to ES6 Class
文章推薦指數: 80 %
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
延伸文章資訊
- 1JavaScript | ES6 中最容易誤會的語法糖Class - 基本用法
Instance 能夠使用Class 內的Method,並藉由Method 存取Object 內的資料。 咦?就算沒寫過,但這樣看起來似乎和JavaScript 的Constructor 及In...
- 2Classes - JavaScript - MDN Web Docs
ECMAScript 6 中引入了類別(class) 作為JavaScript 現有原型程式(prototype-based)繼承的語法糖。類別語法並不是要引入新的物件導向繼承模型 ...
- 3JavaScript Class Fundamentals: Introduction to ES6 Class
A JavaScript class is a blueprint for creating objects. A class encapsulates data and functions t...
- 4JavaScript Class (類別) - Shubo 的程式開發筆記
JavaScript中沒有真正的「類別」實體。 class 宣告出來的本體是「函式」。 換句話說, class 只是宣告函式的一種特別的 ...
- 5JavaScript Classes - W3Schools
Class methods are created with the same syntax as object methods. Use the keyword class to create...