DEV Community

Discussion on: So Functions and Methods are the Same?

Collapse
 
ricobrase profile image
Rico Brase

Great post!

When I'm explaining the difference between functions and methods, I always add, that methods are specific functions running in the context of an object.

Let's imagine, we want to let a user say hello:

// Function

const user = {
    name: "Firstname Lastname"
};

function sayHelloFunction(user) {
    console.log(`Hello, my name is ${user.name}!`);
}

// Somewhere in your code:
sayHelloFunction(user);

// ----------------------------//

// Method
class User {
    constructor(name) {
        this.name = name;
    }

    sayHelloMethod() {
        console.log(`Hello, my name is ${this.name}!`);
    }
}

const user = new User("Firstname Lastname");

// somewhere in your code:
user.sayHelloMethod();
Enter fullscreen mode Exit fullscreen mode

Note, that we don't have to pass a user to the method, since we provided that information implicitly through the context of the user-object, on which the method is called.