☰ See All Chapters |
JavaScript ES6 Classes
JavaScript ES6 is an object oriented programming (OOP) language which supports object oriented programming concepts inheritance, polymorphism, abstraction and encapsulation. From object-oriented programming point of view, Class is like a template or blueprint from which objects are created.
What are the members of JavaScript ES6 class?
Fields/Variables
Constructors
Methods
Inner class and interface
Syntax to write a class in JavaScript ES6
We can declare a class using class keyword as below:
class ClassName{ //constructor //field; //method; } |
We can define classes in single or in maultiple ts files.
Example:
class Box { legth; width; constructor(legth, width) { this.legth = legth; this.width = width; } add(box) { return new Box(this.legth + box.legth, this.width + box.width); } } |
When this complied to JavaScript ES5 below code is created:
var Box = /** @class */ (function () { function Box(legth, width) { this.legth = legth; this.width = width; } Box.prototype.add = function (box) { return new Box(this.legth + box.legth, this.width + box.width); }; return Box; }()); |
Declaring or creating Objects using new keyword in JavaScript ES6
Declaring Objects using new involves two steps.
Declaring a variable. This variable does not define an object. Instead, it is simply a variable that can refer to an object.
Acquiring an actual, physical copy of the object and assign it to that variable. We can do this using the new operator.
Syntax
let variableName = new ClassName(parameter1, parameter2, ...) ; |
Example
var box1 = new Box(0, 10); var box2 = new Box(10, 20); |
Accessing Members of a class in JavaScript ES6
To access members of class variables, we will use the dot (.) operator. The dot operator links the name of the object with the name of the member. For example, to assign the width variable of box the value 100, you would use the following statement:
box.width = 100;
All Chapters