Navigating JavaScript Classes: Understanding Structure, Methods, and Accessors
Introduction to JavaScript Classes
Hello and welcome to our new session on JavaScript classes! Classes in JavaScript resemble blueprints used for creating similar objects. If you're a video game player who regularly creates characters, each character possesses different properties but shares common attributes. In this context, classes act as your templates. In this lesson, we'll explore the structure of classes, their main methods, and examine getters and setters.
Understanding Classes
JavaScript classes are essentially the molds for creating objects. They encompass data and behaviors that belong to the object. The structure for defining a class includes the class keyword followed by the name of the class.
In this Dog class, we have a property called name, which is set in a special function named the constructor(). The constructor is automatically called when we create a new instance of the class.
In object-oriented programming, an "instance" is an object created from a specific class. We can create a new instance in JavaScript using the new keyword:
In this line of code, new Dog('Spot') creates a new instance of the Dog class, with the name property set to 'Spot'. The new keyword is essentially telling JavaScript to create a new object, and then invoke the constructor function on that object.
Within the class, we also often see and use the this keyword. The this keyword in JavaScript is a little complex as it behaves differently depending on the context it is used in. In a class, this refers to the instance of the class. In other words, it refers to the object that is created from the class.
For example, when we use this.name = name; in our constructor, this is referring to the instance of the Dog being created, and this.name is setting the name property of that specific Dog instance.
The instance of the class, such as myDog in this case, is a full-fledged object with properties and behaviors as defined by the class structure. We can easily access these properties, like so:
When you see this code, the dot notation ".name" accesses the name property of myDog and returns its value. It's actually accessing this.name for the myDog object.
So, whenever you see this in a method inside a class, think of this as the object which the method is acting on.
