The ubiquitous JavaScript approach of emulating class-like inheritance hierarchies via functions and prototypes is formalized in ES6 Classes. They’re essentially sugar on top of prototype-based OO, providing a declarative form for class patterns that promote interoperability.
Just like every programming language class, Javascript ES6 supports the following features:
Let's create a class.
Let's look at the code below:
'use strict'; // Example 1: Creating a new class // using the keyword 'class' to define the base class class Biography { // constructor() { } constructor(dob, sex) { this.name = 'John Doe'; this.dob = dob; this.sex = sex; } // method declarations of the class sayName() { console.log('Hi, I am a ', this.name + '.'); } } // Classes are used just like ES5 constructor functions: let p = new Biography(1994, 'Female'); p.sayName(); console.log('My gender is ' + p.sex);
In the above code:
Line 7: We create a class Biography
.
Lines 11 to 15: We declare class properties.
Lines 19 to 21: We instantiate a method sayName()
to log the name property.
Line 28: We instantiate the class on p
variable.
Line 29: We access the class method sayName()
.
Line 30: We access the class properties sex
.
You can play around with the code sample for better understanding.
RELATED TAGS
CONTRIBUTOR
View all Courses