Summary
const myObject = {
name: 'John',
sayHello() {
console.log('Hello');
}
}
Details
In addition to containing properties, objects can contain functions. Functions inside of objects are called methods.
To create a method in JavaScript, first create an object.
const myObject = {
}
Then write the name of the method followed by a pair of parentheses and a pair of curly braces separated by a new line.
const myObject = {
sayHello() {
}
}
Next, write whatever lines of code you want to be a part of the method inside the method’s curly braces.
const myObject = {
sayHello() {
console.log('Hello');
}
}
To call the method, write the object name, a period, and the name of the function, like this:
const myObject = {
sayHello() {
console.log('Hello');
}
}
myObject.sayHello();
Methods can also contain parameters and arguments, just like regular functions.
const myObject = {
sayHello(person) {
console.log('Hello ' + person);
}
}
myObject.sayHello('Jim');
If the object contains properties, use a comma after each key-value pair.
const myObject = {
name: 'John',
sayHello() {
console.log('Hello');
}
}
Multiple methods
You can also have multiple methods. Add a comma after the closing curly brace of a method to add another one after it.
const myObject = {
sayHello() {
console.log('Hello');
},
sayGoodbye() {
console.log('Goodbye');
}
}
Demo
Exercises
Try the following statements in the console:
const myObject = {
sayHello() {
console.log('Hello');
}
}
myObject.sayHello();