By the end of this lesson, you will understand the concept of this, how to use object methods, and the basics of classes in JavaScript.
In JavaScript, this refers to the object that is executing the current function. It can change depending on how a function is called. For example, in a method of an object, this refers to the object itself.
Consider a dog object with a bark method:
const dog = {
name: "Buddy",
bark: function() {
console.log(this.name + " says woof!");
}
};
dog.bark();
File: dog.js
Buddy says woof!
Here, this.name inside the bark method refers to the dog’s name. When we call dog.bark(), it outputs the name “Buddy” and adds “says woof!”.
Object methods are functions stored as object properties. You can use them to perform operations related to that object. They help keep your code organized.
Classes provide a way to create objects with shared methods and properties. Here’s a simple class example:
class Dog {
constructor(name) {
this.name = name;
}
bark() {
console.log(this.name + " says woof!");
}
}
const myDog = new Dog("Max");
myDog.bark();
File: dogClass.js
Max says woof!
Create a Cat class with properties name and age, and a method meow that outputs: “name the cat is age years old and says meow!”. Then, create an instance of the Cat class and call the meow method.
class Cat {
constructor(name, age) {
this.name = name;
this.age = age;
}
meow() {
console.log(this.name + " the cat is " + this.age + " years old and says meow!");
}
}
const myCat = new Cat("Whiskers", 3);
myCat.meow();