Classes in JavaScript ES6
JavaScript Classes are one of the features introduced in the ES6 version of JavaScript. JavaScript Classes are templates for creating JavaScript Objects.
Class is a blueprint of an object. It contains some details and based on these descriptions we can create as many objects as we want.
You can think of a class as a prototype of a User. It contains all the details like name, age, salary, organization, etc based on which the User is created and the good part is that now we can re-use this class for creating multiple users or we can extend some other classes from this class.
Defining Classes
JavaScript classes are similar to JavaScript methods For example,
Types of Methods
- Constructor ::
Constructor functions are basically regular function which starts with a capital letter. Constructor function is used to create multiple instance of an object. Constructor should be executed with new
operator. Main purpose of constructor function is code reusability. A constructor consists of constructor name, properties and method. We use this
to assign values to the properties that are passed to constructor function during the object creation
This Key word ...
<script>
class cars{ constructor(name,color){ this.name=name; this.color = color; } }
var myCar = new cars ("Ford","Red"); var myCarTwo = new cars ("BMW","Black");
console.log(myCar); console.log(myCarTwo); </script>
Constructor functions are basically regular function which starts with a capital letter. Constructor function is used to create multiple instance of an object. Constructor should be executed with
new
operator. Main purpose of constructor function is code reusability. A constructor consists of constructor name, properties and method. We use this
to assign values to the properties that are passed to constructor function during the object creationThis Key word ...
Inheritence :
It allows the child class to invoke the properties, methods, and constructors of the immediate parent class. It is introduced in ECMAScript 2015 or ES6. The super.prop and super[expr] expressions are readable in the definition of any method in both object literals and classes.
Syntax
super(arguments);Example
In this example, the characteristics of the parent class have been extended to its child class. Both classes have their unique properties. Here, we are using the super keyword to access the property from parent class to the child class.