DeveloperBreeze

JavaScript Class with Constructor and Method

javascript
// Class definition for Person
class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // Method to generate a greeting
    greet() {
        return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
    }
}

// Usage of the Person class
const person = new Person('John', 30);
const greeting = person.greet();

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Understanding JavaScript Classes

The extends keyword is used to create a subclass (child class) that inherits from another class (parent class).

class Animal {
  constructor(type, name) {
    this.type = type;
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super('Dog', name);
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak(); // Output: Buddy barks.

Sep 02, 2024
Read More
Code
php

PHP Class and Object Example

No preview available for this content.

Jan 26, 2024
Read More
Code
python

Class with Method

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!