JavaScript Object Methods
JavaScript Object Methods
Donate Now
(https://www.javascripttutorial.net/donation/)
For example, the following adds the greet method to the person object:
let person = {
firstName: 'John',
lastName: 'Doe'
};
person.greet = function () {
console.log('Hello!');
https://www.javascripttutorial.net/javascript-object-methods/ 1/4
29/07/2022, 08:09 JavaScript Object Methods
person.greet();
Output:
Hello!
In this example:
First, use a function expression to define a function and assign it to the greet property of the
person object.
Besides using a function expression, you can define a function and assign it to an object like this:
let person = {
firstName: 'John',
lastName: 'Doe'
};
function greet() {
console.log('Hello, World!');
person.greet = greet;
person.greet();
In this example:
Second, assign the function name to the the greet property of the person object.
https://www.javascripttutorial.net/javascript-object-methods/ 2/4
29/07/2022, 08:09 JavaScript Object Methods
let person = {
firstName: 'John',
lastName: 'Doe',
greet: function () {
console.log('Hello, World!');
};
let person = {
firstName: 'John',
lastName: 'Doe',
greet() {
console.log('Hello, World!');
};
person.greet();
https://www.javascripttutorial.net/javascript-object-methods/ 3/4
29/07/2022, 08:09 JavaScript Object Methods
For example, you may want to define a method that returns the full name of the person object by
concatenating the first name and last name.
Inside a method, the this value references the object that invokes the method. Therefore, you can
access a property using the this value as follows:
this.propertyName
The following example uses the this value in the getFullName() method:
let person = {
firstName: 'John',
lastName: 'Doe',
greet: function () {
console.log('Hello, World!');
},
getFullName: function () {
};
console.log(person.getFullName());
Output
'John Doe'
Summary
When a function is a property of an object, it becomes a method.
https://www.javascripttutorial.net/javascript-object-methods/ 4/4