Contenido del Curso
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Class Methods
Now that we know how to add properties using the constructor, let's explore how to add methods to a class.
Defining and Using Class Methods
These methods typically operate on the object's properties and provide a way to interact with its data.
To define a class method, simply declare a function inside the class without using the function
keyword.
In this example, getInfo
is a method of the Animal
class. Any instance of Animal
can call this method to retrieve information about that particular instance.
How Methods Are Associated with Instances of a Class
When you create an instance of a class, the methods defined inside the class automatically become available to that instance. These methods can access and manipulate the instance's properties using the this
keyword, which refers to the current object.
Think of methods as tools that each object (instance) carries with it. Each object has its own data (properties), but they share the same tools (methods) to interact with that data.
Let's consider the example:
class Animal { constructor(name, type) { this.name = name; this.type = type; } // Class method getInfo() { return `${this.name} is a ${this.type} animal.`; } } const lion = new Animal('Lion', 'Wild'); console.log(lion.getInfo()); // Output: Lion is a Wild animal. const pig = new Animal('Pig', 'Domestic'); console.log(pig.getInfo()); // Output: Pig is a Domestic animal.
In this example, both lion
and pig
are instances of the Animal
class. The getInfo
method is available to both, and it returns different results based on the properties of the specific instance it's called on. This demonstrates how methods are shared across instances but operate on data specific to each one.
Why Use Class Methods?
Class methods define behaviors that are specific to the object. They make code more modular, maintainable, and create a clear separation of responsibilities. Instead of directly manipulating object properties, class methods offer a controlled way to interact with and modify the object's data.
Example with a method that changes object state:
class Animal { constructor(name, type) { this.name = name; this.type = type; } getInfo() { return `${this.name} is a ${this.type} animal.`; } changeType(newType) { this.type = newType; } } const lion = new Animal('Lion', 'Wild'); console.log(lion.getInfo()); // Output: Lion is a Wild animal. lion.changeType('Domestic'); console.log(lion.getInfo()); // Output: Lion is a Domestic animal.
In this example, the changeType
method allows you to update the type
property of the object. This shows how methods can encapsulate logic that directly affects the object's state.
¡Gracias por tus comentarios!