JavaScript ClassesIn JavaScript, classes are the special type of functions. We can define the class just like function declarations and function expressions. The JavaScript class contains various class members within a body including methods or constructor. The class is executed in strict mode. So, the code containing the silent error or mistake throws an error. The class syntax contains two components:
Class DeclarationsA class can be defined by using a class declaration. A class keyword is used to declare a class with any particular name. According to JavaScript naming conventions, the name of the class always starts with an uppercase letter. Class Declarations ExampleLet's see a simple example of declaring the class. Output: 101 Martin Roy 102 Duke William Class Declarations Example: HoistingUnlike function declaration, the class declaration is not a part of JavaScript hoisting. So, it is required to declare the class before invoking it. Let's see an example. Output: Class Declarations Example: Re-declaring ClassA class can be declared once only. If we try to declare class more than one time, it throws an error. Let's see an example. Output: Class expressionsAnother way to define a class is by using a class expression. Here, it is not mandatory to assign the name of the class. So, the class expression can be named or unnamed. The class expression allows us to fetch the class name. However, this will not be possible with class declaration. Unnamed Class ExpressionThe class can be expressed without assigning any name to it. Let's see an example. Test it NowOutput: emp Class Expression Example: Re-declaring ClassUnlike class declaration, the class expression allows us to re-declare the same class. So, if we try to declare the class more than one time, it throws an error. Test it NowOutput: 101 Martin Roy 102 Duke William 103 James Bella 104 Nick Johnson Named Class Expression ExampleWe can express the class with the particular name. Here, the scope of the class name is up to the class body. The class is retrieved using class.name property. Test it NowOutput: Employee Next TopicJS Object |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India