A method is just a function that belongs to a class (or an object). It’s something the object can do.
Example 1 — A simple class with one method
JavaScript Example:
class Person {
sayHello() {
console.log("Hello!");
}
}
const p = new Person();
p.sayHello(); // "Hello!"
sayHello()is a method.- You call it on the object with
p.sayHello().
Example 2 — Method using this
JavaScript Example:
class Person {
constructor(name) {
this.name = name; // property
}
greet() {
console.log(`Hi, I'm ${this.name}`);
}
}
const anna = new Person("Anna");
anna.greet(); // "Hi, I'm Anna"
- In a constructor called with
new,thisrefers to the new object being created.- In this example,
new Person("Anna")creates a new object and assigns it tothisinside theconstructor.
- In this example,
- When a method is called on an instance of a class,
thisrefers to that instance.- So, in the example,
anna.greet()makesthisrefer toannainside thegreet()method.
- So, in the example,
Example 3 — Multiple methods
JavaScript Example:
class Counter {
constructor() {
this.value = 0;
}
increase() {
this.value++;
}
show() {
console.log(this.value);
}
}
const c = new Counter();
c.increase();
c.show(); // 1
Each method adds some behavior to the class:
increase()changes datashow()displays it
In short:
Methods are functions inside a class that let objects do things or react to things.