Languages
[Edit]
EN

JavaScript - create method inside object

0 points
Created by:
Eshaal-Wilkinson
354

In this article, we would like to show you how to create method inside object in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const object = {
    methodName: function(){
        console.log('Some action...');
    }
}

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

 

Practical examples

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

// ONLINE-RUNNER:browser;

const user = {
    id: 1,
    name: 'Tom',
    surname: 'Smith',
    fullName: function(){
        console.log(this.name + ' ' + this.surname)
    }
}

user.fullName();  // Tom Smith

Output:

Tom Smith

Alternative solution

// ONLINE-RUNNER:browser;

const object = new function () {
  this.methodName = function () {
    console.log('Some action...');
  };
}

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

Output:

Some action...
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