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
延伸文章資訊
- 1Day 10: ES6篇- Class(類別) - iT 邦幫忙
真正的JavaScript語言的物件導向設計,是以"原型(Prototype)"為基礎的物件導向,這10幾20年來都沒變過,目前許多樣式、函式庫、框架都是從這個基礎發展出來的,這是我一直 ...
- 2JavaScript | ES6 中最容易誤會的語法糖Class - 基本用法
Instance 能夠使用Class 內的Method,並藉由Method 存取Object 內的資料。 咦?就算沒寫過,但這樣看起來似乎和JavaScript 的Constructor 及In...
- 3JavaScript Class (類別) - Shubo 的程式開發筆記
JavaScript中沒有真正的「類別」實體。 class 宣告出來的本體是「函式」。 換句話說, class 只是宣告函式的一種特別的 ...
- 4Classes - JavaScript - MDN Web Docs
ECMAScript 6 中引入了類別(class) 作為JavaScript 現有原型程式(prototype-based)繼承的語法糖。類別語法並不是要引入新的物件導向繼承模型 ...
- 5[JS] JavaScript 類別(Class) | PJCHENder 未整理筆記
[JS] JavaScript 類別(Class). function constructor 有hoisting 的情況,所以可以寫再後面但在前面使用;但是class constructor ...