DEV Community

Cover image for Methods
G U BHARATH CHANDRA
G U BHARATH CHANDRA

Posted on

Methods

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?
Here window is an object and scrollTo is a function. ie.. scrollTo is a method.

Similarly, console is an object and log 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
Enter fullscreen mode Exit fullscreen mode
  • Shorthand method:
const batman = {
    alias() {
        return "BRUCE WAYNE";
    }
}

batman.alias() // BRUCE WAYNE
Enter fullscreen mode Exit fullscreen mode
  • Arrow function:
const batman = { alias: () => `BRUCE WAYNE`};

batman.alias() // BRUCE WAYNE
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Async methods:

  • Using short-hand syntax:
const batman = {
    async alias() {
        await somePromiseToResolve;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Using arrow functions:
const batman = { alias: async () => {
    await do_something;
  } 
};
Enter fullscreen mode Exit fullscreen mode

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!

Oldest comments (0)