EN
JavaScript - create method inside object
0 points
In this article, we would like to show you how to create method inside object in JavaScript.
Quick solution:
xxxxxxxxxx
1
const object = {
2
methodName: function(){
3
console.log('Some action...');
4
}
5
}
6
7
object.methodName(); // Some action...
In this example, we create a method that displays our user
object full name.
xxxxxxxxxx
1
const user = {
2
id: 1,
3
name: 'Tom',
4
surname: 'Smith',
5
fullName: function(){
6
console.log(this.name + ' ' + this.surname)
7
}
8
}
9
10
user.fullName(); // Tom Smith
Output:
xxxxxxxxxx
1
Tom Smith
xxxxxxxxxx
1
const object = new function () {
2
this.methodName = function () {
3
console.log('Some action...');
4
};
5
}
6
7
object.methodName(); // Some action...
Output:
xxxxxxxxxx
1
Some action...