Call one method from another method in same class in JavaScript
In this tutorial, we are going to learn how to call the one method from another method in same class using JavaScript.
Consider, we have the following JavaScript class in our code:
class User {
name() {
console.log('John');
}
getName() {
}
}
Now, we need to call the name()
method inside the getName()
method in User class.
Using this keyword
To call the one method from a another, we can use the this keyword in JavaScript.
Here is an example:
class User {
name() {
console.log("John");
}
getName() {
this.name(); // calling name() method
}
}
const user = new User();
console.log(user.getName); // "John"