loading

JS Object Methods

JavaScript Object Methods

Object methods are actions that may be applied to objects.

A method is a function definition saved as a property value.

PropertyValue
firstNameJohn
lastNameDoe
age50
eyeColorblue
fullNamefunction() {return this.firstName + ” ” + this.lastName;}

Example

				
					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.

Accessing Object Methods

You access an object method using the following syntax:

Js Object Methods -

When you invoke the fullName property with (), it executes like a function:

Example

				
					name = person.fullName();
				
			

If you access the fullName property without (), you will get the function definition:

Example

				
					name = person.fullName;
				
			

Adding a Method to an Object

Adding a new method to an object is simple:

Example

				
					person.name = function () {
  return this.firstName + " " + this.lastName;
};
				
			

Using JavaScript Methods

This example employs the JavaScript toUpperCase() function to transform a string to uppercase:

Example

				
					person.name = function () {
  return (this.firstName + " " + this.lastName).toUpperCase();
};
				
			
Share this Doc

JS Object Methods

Or copy link

Explore Topic