Зміст курсу
JavaScript Data Structures
JavaScript Data Structures
Properties in Methods
Let's dive deeper into the usage of object methods and explore how methods use the this
keyword to access object properties.
Access Object Properties in Methods
When we define a method within an object, we can access the object's properties using the this
keyword. this
refers to the object called the method, allowing us to interact with its properties. Let's illustrate this concept with an example:
In the getInfo
method, this
refers to the furniture
object and represents the entire object's inner content.
Practical Example
In methods, we can access object properties through this
and then use dot notation to access the specific properties as usual.
In the example below, the methods getColor
, addProperty
, and modifyProperty
use this
to access the furniture
property and perform various operations.
getColor
logs the wardrobe color to the console usingthis
to refer to the object's properties;addProperty
adds new properties to the furniture object. It takes two parameters:propertyName
(the name of the new property) andpropertyValue
(the value to assign to the new property);modifyProperty
changes the value of an existing property in thefurniture
object. It takes two parameters:propertyName
(the property name to modify) andpropertyValue
(the new value to assign to the property).
const furniture = { type: "wardrobe", manufacturer: "Belgium", color: "wenge magic", getColor() { console.log(this.color); }, addProperty(propertyName, propertyValue) { this[propertyName] = propertyValue; }, modifyProperty(propertyName, propertyValue) { this[propertyName] = propertyValue; }, }; // Access the `color` property of the `furniture` and log it to the console. furniture.getColor(); // Output: wenge magic // Add a new property to the `furniture` object using the `addProperty` method. furniture.addProperty("material", "wood"); console.log(furniture.material); // Output: wood // Modify an existing property using the `modifyProperty` method. furniture.modifyProperty("color", "oak"); console.log(furniture.color); // Output: oak
Note
Using the
this
keyword is essential in object methods. It ensures that the method works with the specific object that is called it, even if the name is unknown in advance. This avoids potential issues, such as copying methods from one object to another with a different name.
Дякуємо за ваш відгук!