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

class Book {
  constructor(title, author, isbn) {
    this.title = title;
    this.author = author;
    this.isbn = isbn;
  }

  getDetails() {
    return `${this.title} by ${this.author} (ISBN: ${this.isbn})`;
  }
}

class Library {
  constructor() {
    this.books = [];
  }

  addBook(book) {
    this.books.push(book);
  }

  removeBook(isbn) {
    this.books = this.books.filter(book => book.isbn !== isbn);
  }

  listBooks() {
    return this.books.map(book => book.getDetails()).join('\n');
  }
}

const library = new Library();
const book1 = new Book('The Great Gatsby', 'F. Scott Fitzgerald', '9780743273565');
const book2 = new Book('1984', 'George Orwell', '9780451524935');

library.addBook(book1);
library.addBook(book2);
console.log(library.listBooks());
// Output:
// The Great Gatsby by F. Scott Fitzgerald (ISBN: 9780743273565)
// 1984 by George Orwell (ISBN: 9780451524935)

JavaScript classes provide a powerful and intuitive way to structure your code using object-oriented principles. By understanding how to use constructors, inheritance, static methods, private fields, and getters/setters, you can write more organized and maintainable code. This tutorial has covered the fundamentals and some advanced features of JavaScript classes, giving you the tools you need to effectively use classes in your projects.

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!