Bringing Classes to Life: Attributes and Methods in JavaScript

Lesson Overview

Hello there! Today, we're diving into JavaScript classes, focusing on attributes and methods. Attributes are characteristics, whereas methods define behaviors. You'll learn these concepts through a Dog class. By the end of the lesson, you should be able to use attributes and methods in JavaScript classes effectively.

Understanding Attributes in JavaScript Classes

Think of attributes as properties. For a Dog class, the attributes might include name: "Fido", breed: "Poodle", color: "White". These attributes describe the characteristics of a dog like Fido.

Creating Attributes in a JavaScript Class

We add attributes to the class constructor. Below, we're setting the name, breed, and color for the Dog class:

JavaScript
class Dog {
    name = 'Fido';
    breed = 'Poodle';
    color = 'White';
}

When we create an instance:

JavaScript
const fido = new Dog();
console.log(fido.name); // Prints: Fido
console.log(fido.breed); // Prints: Poodle
console.log(fido.color); // Prints: White

We see Fido, an object of the Dog class.

Understanding Methods in JavaScript Classes

Methods are actions that instances of a class can perform. For the Dog class, behaviors might include bark(), eat(), and sleep(). Methods are functions defined within the class.

Creating Methods in a JavaScript Class

Let's make Fido more interesting with some activities. We can give him actions like barking, eating, and sleeping by adding methods to the 'Dog' class.

JavaScript
class Dog {
    name = 'Fido';
    breed = 'Poodle';
    color = 'White';

    bark() {
        console.log(`Woof Woof!`);
    }

    eat(food) {
        // "this" corresponds to the reference to the current Dog class instance
        console.log(`${this.name} is eating ${food}.`);
    }

    sleep() {
        console.log(`Zzz...`);
    }
}

Here, bark, eat, and sleep methods define the behavior of a Dog object. A particular instance of Dog can now bark, eat, and sleep. Note the use of this in the eat(food) method - this way we reference the class attribute, where this corresponds to the reference to the current instance of the Dog class.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal