Skip to main content

What is class in JavaScript ? How to define and use it?

accessing class properties
In JavaScript, a class is a blueprint for creating objects with similar properties and methods. It provides a way to define a particular type of object, encapsulating data for the object and methods to operate on that data. Classes were introduced in ECMAScript 2015 (ES6) to mimic the class-based inheritance found in other object-oriented programming languages. 

Here's how you define a class in JavaScript:

      In this example:
  •  MyClass is the name of the class.
  • Constructor is a special method for creating and initializing objects created with a class. It is executed automatically when a new object is created with the new keyword. 
  • Method1 and method2 are methods of the class, defining behaviour for instances of the class. To create an instance of a class, you use the new keyword:
This creates a new object obj based on the MyClass blueprint, with property1 set to 'value1' and property2 set to 'value2'. 

 You can then access properties and methods of the object using dot notation:
Classes in JavaScript also support inheritance. 

You can use the extends keyword to create a subclass:
Kindly visit my first post about function here .
Happy coding.

Comments

Popular Posts

OnePlus Unveils Revolutionary Mechanical Keyboard - A Game-Changer in the Tech World!

A good and surprisingly unique first-time mechanical keyboard, courtesy of Keychron’s impeccable design

OnePlus Monitor X27: A Stunning Display of Performance and Versatility

The OnePlus Monitor X27 is a 27-inch monitor aimed primarily at those who need to push the envelope when it comes to gaming, and maybe their professional life.