JS Tutorial
Object methods are actions that may be applied to objects.
A method is a function definition saved as a property value.
| Property | Value |
|---|---|
| firstName | John |
| lastName | Doe |
| age | 50 |
| eyeColor | blue |
| fullName | function() {return this.firstName + ” ” + this.lastName;} |
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
In the previous example, this corresponds to the person object.
This.firstName refers to the firstName attribute of a person.
this.lastName attribute refers to a person’s last name.
You access an object method using the following syntax:
When you invoke the fullName property with (), it executes like a function:
name = person.fullName();
If you access the fullName property without (), you will get the function definition:
name = person.fullName;
Adding a new method to an object is simple:
person.name = function () {
return this.firstName + " " + this.lastName;
};
This example employs the JavaScript toUpperCase() function to transform a string to uppercase:
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};
CodingAsk.com is designed for learning and practice. Examples may be made simpler to aid understanding. Tutorials, references, and examples are regularly checked for mistakes, but we cannot guarantee complete accuracy. By using CodingAsk.com, you agree to our terms of use, cookie, and privacy policy.
Copyright 2010-2024 by Refsnes Data. All Rights Reserved.