Understanding Object Methods in JavaScript
JavaScript Object Methods Introduction to Object Methods Object methods in JavaScript are actions that can be executed on objects. These methods are essentially functions that a...
JavaScript Object Methods
Introduction to Object Methods
Object methods in JavaScript are actions that can be executed on objects. These methods are essentially functions that are assigned as values to object properties.
Example of Object Properties and Methods
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, fullName is a method that returns the full name of the person by accessing the firstName and lastName properties of the object.
The this Keyword
Within an object method, the keyword this refers to the object on which the method was called. For example, in the fullName method, this.firstName refers to the firstName property of the person object.
How to Call Object Methods
To invoke an object method, use parentheses after the method name. Calling a method with parentheses executes the function, whereas omitting the parentheses returns the function definition itself.
Adding Methods to Objects
Methods can be added to an object by assigning a function to a property. For instance, in the person object example, the fullName method is created by assigning a function to the fullName property.
Using JavaScript String Methods
JavaScript methods like toUpperCase() can be used within object methods to manipulate strings. For example, converting a string to uppercase can be achieved easily.
Summary
- Methods are functions stored as object properties.
- Use parentheses to call a method:
person.fullName(). - Within methods,
thisrefers to the object. - Methods can be added to objects by assigning a function to a property.
Further Reading
For more information on JavaScript objects, you may explore topics such as object properties, object constructors, and object prototypes.