So what are methods?
Methods are basically functions that are defined inside an object.
Let's see that with an example: π
To scroll to a particular position we use
window.scrollTo(x)
right?
Herewindow
is an object andscrollTo
is a function. ie.. scrollTo is a method.Similarly,
console
is an object andlog
is a function and since it lives inside a function, we call it a method.
Creating our own methods: π
- The regular way:
const batman = {
alias: function(){
return "BRUCE WAYNE";
}
}
batman.alias() // BRUCE WAYNE
- Shorthand method:
const batman = {
alias() {
return "BRUCE WAYNE";
}
}
batman.alias() // BRUCE WAYNE
- Arrow function:
const batman = { alias: () => `BRUCE WAYNE`};
batman.alias() // BRUCE WAYNE
Generally, shorthand methods are preferred, arrow functions are best used when you know that you don't need the scope of this
since arrow functions don't have the scope of this
.
Why and when not to use arrow functions?
I have explained that in the previous post in this series "Arrow Functions".
Things you must know about methods π
Methods are not constructors, and we cannot instantiate them like constructors.
It will throw a TypeError. π¦
new batman.alias() //TypeError: batman.alias is not a constructor
Async methods:
- Using short-hand syntax:
const batman = {
async alias() {
await somePromiseToResolve;
}
}
- Using arrow functions:
const batman = { alias: async () => {
await do_something;
}
};
The same way we can use methods in Generator functions
as well which we will see in the upcoming posts in this series.
Wrapping up
Well, we just understood what methods are and how to use them in different and efficient ways.
Stay tuned for further posts in this series. π
See you in the next post Immediately invoked function expressions
. π
Thank you!
Top comments (0)