What's the difference between a method and a function?
In programming, a method is a function that is associated with an object or a class. It is a piece of code that performs a specific task or action on the object or class it is attached to. Methods are used to encapsulate behaviour that is specific to the object or class they belong to.
On the other hand, a function is a piece of code that performs a specific task or action, independent of any specific object or class. Functions are used to encapsulate behaviour that is not specific to any particular object or class but can be used by multiple parts of a program.
Here is an example to illustrate the difference:
javascript
class
Car {
constructor(
make, model) {
this.
make = make;
this.
model = model;
this.
speed =
0;
}
accelerate() {
this.
speed +=
10;
console.
log(
`The ${this.make} ${this.model} is now going ${this.speed} mph.`);
}
}
const myCar =
new
Car(
'Toyota',
'Corolla');
myCar.
accelerate();
// "The Toyota Corolla is now going 10 mph."
In this example, accelerate()
is a
method of the Car
class. It is associated with the myCar
object, and it updates the speed
property of that
object.
javascript
function
addNumbers(
a, b) {
return a + b;
}
const result =
addNumbers(
2,
3);
console.
log(result);
// 5
In this example, addNumbers()
is a
function that takes two arguments, a
and b
, and returns their sum. It is not associated
with any particular object or class and can be used anywhere in the program
where addition is needed.