Languages
[Edit]
EN

JavaScript - add method to existing object

0 points
Created by:
GamerGoals22
244

In this article, we would like to show you how to add method to the existing object in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const object = {}

// add method to object
object.methodName = function () {
    console.log('Some action...');
}

object.methodName(); // Some action...

 

Practical example

In this example, we add a method that displays our user object full name.

// ONLINE-RUNNER:browser;

const user = {
    id: 1,
    name: 'Tom',
    surname: 'Smith',
}

// add method to user object
user.getFullName = function () {
    console.log(this.name + ' ' + this.surname)
}

user.getFullName(); // Tom Smith

Output:

Tom Smith
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join