Method vs. Function

Sometimes the term “method” is used as a synonym for a “function”. In JavaScript and TypeScript there is a clear
distinction: When a function is a property of an object, then it is called a method. This regulation is made because
functions can have a different value for this depending on their association with an object.

Function:

1
2
3
4
5
6
7
'use strict';

function someFunction(this: unknown): void {
console.log(`I am a function and my this value is "undefined"`, this);
}

someFunction();

Method:

1
2
3
4
5
6
7
8
9
10
'use strict';

const person = {
name: "Benny",
someMethod: function () {
console.log(`I am a method and my this value is "object"`, this);
}
}

person.someMethod();

If you turn an arrow function expression into a method, you will notice that the value of this switches to the global object:

1
2
3
4
5
6
7
8
9
10
'use strict';

const person = {
name: "Benny",
someMethod: () => {
console.log(`I am an arrow function and my this value is the global object.`);
}
}

person.someMethod();