JAVASCRIPT CLASSES

Lavanya



JavaScript classes 


In JavaScript, classes are a special type of function. They can be defined similarly to function declarations and function expressions.

A JavaScript class contains various members within its body, including methods and a constructor. Classes are executed in strict mode, meaning any silent errors or mistakes in the code will throw an error.

The class syntax consists of two components:
  • Class declarations
  • Class expressions

Class declarations

A class is defined using a class declaration, where the `class` keyword is followed by the class name. In accordance with JavaScript naming conventions, class names must begin with an uppercase letter.

Example 


Here’s a basic example of how to declare a class.

// Class Declaration
class Person {
  // Constructor method
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // Method to introduce the person
  introduce() {
    console.log(`Hi, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

// Creating an instance of the Person class
const person1 = new Person('Alice', 25);

// Calling the method on the instance
person1.introduce(); 

Output: 

Hi, my name is Alice and I am 25 years old.

Re declare class

A class can only be declared once. Attempting to declare the same class more than once will result in an error.

// Declaring a class
class MyClass {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
}

// Trying to re-declare the same class in the same scope
// Uncommenting the next line will result in a SyntaxError
// class MyClass {}

// Creating an instance of the class
const instance = new MyClass('Alice');
instance.greet(); 

Output: 

Hello, Alice!

Class expressions

A class can also be defined using a class expression, where assigning a name to the class is optional. Class expressions can be either named or unnamed. Unlike class declarations, class expressions allow us to retrieve the class name.

Example 

Unnamed class expression

A class can be defined without being assigned a name.

// Unnamed class expression
const MyClass = class {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
};

const instance = new MyClass('John');
instance.greet(); 

Output: 

Hello, John

Re-declaring class

Unlike class declarations, class expressions allow re-declaration of the same class. However, attempting to re-declare a class will result in an error.

// First class expression
const MyClass = class {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
};

const instance1 = new MyClass('Alice');
instance1.greet(); 

Output:

 Hello, Alice!




Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send