<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
class Pet{
constructor(name, age) {
this.name = name
this.age = age
}
toString() {
return `name : ${this.name}\nage: ${this.age}`
}
}
const pet = new Pet('cloud', 6)
alert(pet)
console.log(pet + '')
</script>
</head>
<body>
</body>
</html>
### Key Elements of the `Pet` Class
- **Constructor**: Defines the `Pet` class with a constructor accepting `name` and `age` parameters, which are assigned to the instance.
- **`toString` Method**: Provides a custom string representation for instances of the `Pet` class. When a `Pet` instance is converted to a string (explicitly or implicitly), this method returns a string containing the pet's name and age.
### Usage of the `Pet` Instance
- An instance of the `Pet` class is created with the name `'cloud'` and age `6`, and stored in the variable `pet`.
- The `alert` function is used to display the pet's details. Since `alert` expects a string, it implicitly calls the `pet.toString()` method, resulting in the alert showing the formatted string "name : cloud\nage: 6".
- The `console.log` statement logs the pet instance concatenated with an empty string (`pet + ''`). This operation triggers the `toString` method implicitly, logging "name : cloud\nage: 6" to the console.
### How It Works
When JavaScript needs to convert an object to a string—whether for concatenation operations, passing an object to `alert`, or other cases where a string representation is required—it automatically calls the object's `toString` method if one is available. The custom `toString` method defined in the `Pet` class ensures that instances of `Pet` are represented as readable strings indicating the pet's name and age, both in the alert dialog and in the console log.
### Practical Implications
Defining a `toString` method in custom classes is a helpful practice for debugging and logging purposes, as it allows objects of these classes to be logged in a human-readable format easily. This makes it easier to inspect instances during development and can also be useful for displaying object information to end-users in a formatted way.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 9) Override (2) | 2025.01.01 |
---|---|
chapter 9) declair class and new instance (0) | 2024.12.31 |
chapter 9) Static keyword (0) | 2024.12.29 |
chapter 9) use to array (1) | 2024.12.28 |
chapter 9) combination get keyword and set keyword (0) | 2024.12.27 |