JavaScript Object Methods
What are Object Methods?
Methods areactions that can be performed on objects.
Methods arefunctions stored asproperty values.
Example
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
returnthis.firstName + " " +this.lastName;
}
};
| Property | Value |
|---|---|
| firstName | John |
| lastName | Doe |
| age | 50 |
| fullName | function() { return this.firstName + " " + this.lastName; } |
Thethis Keyword
In an object method,this refers to the object.
Example 1
firstName: "John",
lastName: "Doe",
id: 5566,
getId: function() {
returnthis.id;
}
};
let number = person.getId();
In the example above,this refers to theperson object.
this.id means theid property of theperson object.
Example 2
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
returnthis.firstName + " " +this.lastName;
}
};
In the example above,this refers to theperson object.
this.firstName means thefirstName property of theperson object.
this.lastName means thelastName property of theperson object.
Accessing Object Methods
Tocall an object method, addparentheses ():
Without parentheses you get the function itself.
Syntax
If you call a methodwith parentheses, it willexecute as a function:
If you call a methodwithout parentheses, it will return thefunction definition:
Adding a Method to an Object
You can add a method to an object byassigning a function to a property:
Example
person.name = function () {
return this.firstName + " " + this.lastName;
};
In the example above,person.name is a property with a function assigned to it.
Adding a JavaScript Method
This example uses the JavaScripttoUpperCase() method to convert a text to uppercase:
Example
return (this.firstName + " " + this.lastName).toUpperCase();
};
Summary
- Methods are functions stored asobject properties
- Call a method with parentheses:person.fullName()
- In methods,this refers to the object
- You canadd methods to objects by assigning afunction to a property

