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.
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.
We add attributes to the class constructor. Below, we're setting the name
, breed
, and color
for the Dog
class:
JavaScript1class Dog { 2 name = 'Fido'; 3 breed = 'Poodle'; 4 color = 'White'; 5}
When we create an instance:
JavaScript1const fido = new Dog(); 2console.log(fido.name); // Prints: Fido 3console.log(fido.breed); // Prints: Poodle 4console.log(fido.color); // Prints: White
We see Fido, an object of the Dog
class.
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.
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.
JavaScript1class Dog { 2 name = 'Fido'; 3 breed = 'Poodle'; 4 color = 'White'; 5 6 bark() { 7 console.log(`Woof Woof!`); 8 } 9 10 eat(food) { 11 // "this" corresponds to the reference to the current Dog class instance 12 console.log(`${this.name} is eating ${food}.`); 13 } 14 15 sleep() { 16 console.log(`Zzz...`); 17 } 18}
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.
Let's create an instance of the Dog
class and call its methods:
JavaScript1const fido = new Dog(); 2 3console.log(fido.name); // Prints: Fido 4console.log(fido.breed); // Prints: Poodle 5console.log(fido.color); // Prints: White 6 7fido.bark(); // Prints: Woof Woof! 8fido.eat("bone"); // Prints: Fido is eating bone. 9fido.sleep(); // Prints: Zzz...
With the use of attributes and methods, we've been able to bring our Dog
class to life.
That's it! With attributes and methods, you can make JavaScript classes more interactive. In this lesson, using the Dog
class, we've added and used attributes and methods. Up next are some exercises for you to practice and master these concepts. Happy coding!